I have the following strings:
let str1 = "5 - 3 + 2 * 5"; // str1 = 20
let str2 = "123 / 3 + 4 * 0.5 - 55 + 1"; // str2 = -31,5
carriers, numbers and number of numbers may vary.
I need to do arithmetic operations on it with the operators that appear between each number and from left to right.
So far I have tried the following:
let arr1 = str1.split(' ');
let arr2 = str2.split(' ');
*arr1 = ["123", "/", "3", "+", "4", "*", "0.5", "-", "55", "+", "1"]*
*arr2 = ["5", "-", "3", "+", "2", "X", "5"]*
let tot = 0;
let _num = 0;
arr.forEach((e) => {
if (tot==0) {
tot = Number(e);
} else {
if (e == '+' || e == '-' || e == 'X' || e == '/') {
let sig = e;
} else {
_num = Number(e);
if (sig=='+') {
tot += _num
} else if (sig=='-') {
tot -= _num
} else if (sig=='X') {
tot *= _num
} else if (sig=='/') {
tot /= _num
}
};
}
});
with the following result
for arr1 , the total is tot = 150
for arr2, the total is tot = 186.5
because it does the operations with the last operator in the array.
When the result should be the following:
*arr1 = ["123", "/", "3", "+", "4", "*", "0.5", "-", "55", "+", "1"]*
127 / 3 = 41
41 + 4 = 45
45 * 0,5 = 22,5
22,5 - 55 = -32,5
-32,5 + 1 = -31,5
tot = -31.5
*arr2 = ["5", "-", "3", "+", "2", "X", "5"]*
5 - 3 = 2
2 + 2 = 4
4 * 5 = 20
tot = 20
NOTE: I am learning to program in javascript and it is appreciated that they take me out of this quagmire.
In the input string you have
*
but in the loop you are checking forX
:Surely the simplest way is by using eval
As you can see on the linked page, it is recommended to limit the use of
eval
because depending on how it is used, it could represent a risk. If you use it in code that is only accessible by you, and you use it carefully you should have no problems.Another thing to note is the concept of operator precedence . As you will see, the result of applying eval to the string
123 / 3 + 4 * 0.5 - 55 + 1
gives as a result-11
instead of-31,5
this is because first the divisions and multiplications are performed and then the additions and subtractionsTo "force" the order from left to right, use parentheses.
Something different than seen:
Finally, to avoid looking for the first value, I assign it initially with the calculation
What is perhaps a little difficult to understand is
this is an Object with the functions previously defined, example for the "+" I assign the sum function