F
F
Fedor2018-03-24 16:17:50
JavaScript
Fedor, 2018-03-24 16:17:50

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;
        };
    };

Is everything okay with this decision or is it a crooked bike?
If that the whole project is here: https://github.com/FedorPereverzev/Calculator-with...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kalombyr, 2018-03-24
@Seagul

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 question

Ask a Question

731 491 924 answers to any question