I'm in the midst of creating a function operate(string)
that will accept an input like operate("1 + 4 - 2')
or operate("1 * 6 / 3)
that will return the mathematically calculated value, in these examples it would be 4
or 1
. Here is my JavaScript code so far:
// This functionfunction operate(string) { let numbers = string.split(" ") let operators = [] numbers.map((item, index) => { if(item.match(/^[0-9]+$/) != null) { numbers[index] = Number(item) } }) console.log(numbers) // [ 141, '+', 12, '-', 2 ] let total = numbers[0] // 141 numbers.splice(0, 1) let shortOperation; // [ '+', 12 ] for(let i = 0; i <= 2; i++) { shortOperation = numbers.slice(0, 2) numbers.splice(0, 3) // [ '-', 2 ] switch(shortOperation[0]) { case "+": total += shortOperation[1] case "-": total +- shortOperation[1] case "*": total *= shortOperation[1] case "/": total /= shortOperation[1] } } return total}const sample = "141 + 12 - 2"console.log(operate(sample))
For some apparent reason, it returns 153
, when it should be 151
. Why, and how can this issue be resolved (and don't worry about the order of operations, it's fine as it is with a left-to-right approach)?
I've been at it for about 2 hours, with minimal success.