I have a script that identifies operators in an array and uses them to calculate based on another array. Below is the script:
function interpret(...args) {
let operators = args[1]; //access the operators array
let values = args[2] //numbers except the first one
return values.reduce((ac, val, i) => {
//check the operator at index 'i' while iterating through 'values'
if (operators[i] === '+') return ac + val;
if (operators[i] === '-') return ac - val;
if (operators[i] === '*') return ac * val;
if (operators[i] === '/') return ac / val;
else return -1;
}, args[0]) //'ac' initially set to first value
}
console.log(interpret(1, ["+"], [1]))
console.log(interpret(4, ["-"], [2]))
console.log(interpret(1, ["+", "*"], [1, 3]))
console.log(interpret(5, ["+", "*", "-"], [4, 1, 3]))
console.log(interpret(10, ['*', '$', '+'], [5, 3, 2])) //Fails in this case and returns 1
Please assist in resolving this issue. Thank you