0

I was wondering how I could take an array with a math problem in it and do the math problem. For example, if I had the array: ["1","+","2","*","3"] how can I preform 1 + 2 x 3

I tried to use this: (ops is the array containing the operation)

 ops = temp.split(" ");
 for(let i = 0; i > ops.length / 2; i++) {
   if (ops[i + 1] == "+") {
     ops[i + 2] = +ops[i] + +ops[i + 2];
      ops.splice(i, i)
      ops.splice(i + 1, i + 1)
   }
 }
  console.log(ops);

I only tried it with addition but it didn't seem to do anything.

  • there's always `eval` - though there's a better suggestion in [never use eval](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!) section of the `eval` docs – Jaromanda X Nov 06 '22 at 22:28
  • Is order of operations required? – kelsny Nov 06 '22 at 22:38

1 Answers1

-1

This code could get very very complicated depending on how sophisticated you want it to be (do you care about operator precedence? parentheses?). However, you currently seem to be totally barking up the wrong tree - there's no need to modify the array in place like you're doing, or peek ahead (i.e. access ops[i + 1] or ops[i + 2]).

Generally, any kind of simple parsing job like this looks like this: loop through the array, looking at one element at a time. Maintain some variables that in some sense keep track of "what's going on" so far in the array, basically the current state of the parser. Update those variables based on the current character. At the end of the loop, the variables somehow tell you the result.

For example, assuming the simplest case, that you just want:

  1. Parse arrays of the form [number, operator, number, operator, number, ...]
  2. Evaluate from left to right (ignore operator precedence)

Then the code would be something like this (untested):

let currentOperator = "+";
let runningTotal = 0;
for (int i = 0; i < ops.length; i++)
{
    let op = ops[i];
    if (op == "+" || op == "-" || op == "*" || op == "/")
    {
        currentOperator = op;
    }
    else
    {
        if (currentOperator == "+")
        {
            runningTotal = runningTotal + parseInt(op);
        }
        else if (currentOperator == "-")
        {
            runningTotal = runningTotal - parseInt(op);
        }
        else if (currentOperator == "*")
        {
            runningTotal = runningTotal * parseInt(op);
        }
        else if (currentOperator == "/")
        {
            runningTotal = runningTotal / parseInt(op);
        }
    }
}
Jack M
  • 4,769
  • 6
  • 43
  • 67
  • hmm, fails the precedence of operators. Also, concatenates for addition until the first non addition operator is encountered. (for the OP's input -> `01` -> `012` -> `36`) – pilchard Nov 06 '22 at 22:42
  • @pilchard True - have to `parseInt` the numbers. – Jack M Nov 06 '22 at 22:50