Answer the question
In order to leave comments, you need to log in
Wrote a calculator without eval(). How viable is this approach?
I asked myself to write an ordinary calculator. You can poke the result here: https://fedorpereverzev.github.io/Calculator-witho... The easiest solution was to use eval (), but then I read that this is not the best idea. As a result, I wrote a function that takes a string as input, splits it into an array, and performs calculations by sign
const antiEval = (str) => {
let arr = str.split(' ');
switch (arr[1]) {
case '+':
return Math.round((+arr[0] + +arr[2]) * 100) / 100;
break;
case '-':
return Math.round((+arr[0] - +arr[2]) * 100) / 100;
break;
case '/':
return Math.round((+arr[0] / +arr[2]) * 100) / 100;
break;
case '*':
return Math.round((+arr[0] * +arr[2]) * 100) / 100;
break;
};
};
Answer the question
In order to leave comments, you need to log in
In my opinion, it's better to build a tree ... It's
better to parse a string in a "step by step" mode, i. look at each character and build a tree.
Since operations have their own priority, and even if there are brackets, then you can’t get off with a simple array.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question