-2

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()?

Aivaras P
  • 166
  • 1
  • 2
  • 14
  • You can't put arithmetic operators in an array like that, aren't you getting a syntax error? You need to make it a string with quotes. `'+'`. – Barmar Feb 04 '16 at 07:41
  • It does, but it's just like a part of text to formulate my question, not a code to run. I'll update the question for it not to be misleading :) – Aivaras P Feb 04 '16 at 07:48
  • See http://stackoverflow.com/questions/21202716/using-select-value-as-operator/21202809#21202809 for how to map operator strings to functions that implement that operation. – Barmar Feb 04 '16 at 07:55
  • Really? You don't use eval for the "challenge" but now you're asking for the solution here? Try it yourself and read the forum rules before you post again. – SubliemeSiem Feb 25 '16 at 08:24

2 Answers2

0

Use this,

function notEval(fn) {
  return new Function('return ' + fn)();
}
numbers = [1, 1, '+', 2, '*', 3, '-', '(', 4, '*' , 5, '+', 2,' /', 5, ')'];
console.log( numbers.join('') + ' = ' +  notEval(numbers.join('')) );

Courtesy.

Community
  • 1
  • 1
rrk
  • 15,677
  • 4
  • 29
  • 45
  • Space magic :)) I'll have to get a better look at this to fully understand how it works.. – Aivaras P Feb 04 '16 at 07:53
  • 1
    Constructing a function is equivalent to using `eval`, it's just different syntax. – Barmar Feb 04 '16 at 07:53
  • @Barmar Oh, I didn't know that. So does that means the same cons of `eval` applies here too? – rrk Feb 04 '16 at 07:54
  • Yes, it has all the same problems. They both run the Javascript interpreter over the string. – Barmar Feb 04 '16 at 07:56
  • @Barmar Thanks for the info man. So do we need to have some kind of custom interpreter for solving this? – rrk Feb 04 '16 at 08:00
  • Isn't that the whole point of the exercise, to figure out how to write that interpreter? See my answer for the basics. – Barmar Feb 04 '16 at 08:03
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank You. I'll try to look deeper into the link You suggested. http://stackoverflow.com/questions/21202716/using-select-value-as-operator/21202809#21202809 – Aivaras P Feb 20 '16 at 11:18