Search code examples
javascriptarraysevalcalculatorequation

adding / dividing / multiplying numbers and operators from array in javascript without eval()


I'm making a calculator. And the challenge is not to use eval(). I made an array from all the inputs that looks like this:

numbers = [1,1,'+',2,'*',3,'-','(',4,'*',5,'+',2,'/',5,')'];

Then i convert this array to a string, remove the , and i get a string like this:

numberString = "11+2*3-(4*5+2/5)";

So my question is, what is the way to correctly calculate the result of this equation without using eval()?


Solution

  • Use an object to map operator strings to functions that implement the operator.

    var operators = {
        '+': function(x, y) { return x + y; },
        '-': function(x, y) { return x - y; },
        '*': function(x, y) { return x * y; },
        '/': function(x, y) { return x / y; }
    };
    

    The ( function should push the state onto a stack, and ) should pop the stack.