#Evaluating a string as a mathematical expression

2 messages · Page 1 of 1 (latest)

primal tiger
#

you don't do anything with this
numbers.splice(0, 3); // [ '-', 2 ]

#

I changed your code slightly:

// all assuming the expression is in format number, operator, number...
// and numbers are all positive, also not checking for operator precence
function operate(string) {
     let expression = string.split(" ");

     expression.map((item, index) => {
          if (item.match(/^[0-9]+$/) != null) {
               expression[index] = +item;
          }
     });

     console.log(expression); // [ 141, '+', 12, '-', 2 ]
     let total = expression[0]; // 141

     // loop by increasing by 2 to get nextNumber at new index
     for (let i = 1; i < expression.length; i += 2) {
          const operator = expression[i];
          const nextNumber = expression[i + 1];

          switch (operator) {
               case "+":
                    total += nextNumber;
                    break;
               case "-":
                    total -= nextNumber;
                    break;
               case "*":
                    total *= nextNumber;
                    break;
               case "/":
                    total /= nextNumber;
                    break;
          }
     }

     return total;
}

const sample = "141 + 12 - 2";

console.log(operate(sample)); // 151