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:
- Parse arrays of the form
[number, operator, number, operator, number, ...]
- 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);
}
}
}