mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 19:19:07 +01:00
33 lines
597 B
JavaScript
33 lines
597 B
JavaScript
|
function calc(expr) {
|
||
|
expr = expr.split(' ');
|
||
|
|
||
|
let stack = [];
|
||
|
|
||
|
for (let token of expr) {
|
||
|
if (token == '+' || token == '-' || token == '*' || token == '/') {
|
||
|
let op2 = stack.pop();
|
||
|
let op1 = stack.pop();
|
||
|
let result;
|
||
|
|
||
|
switch (token) {
|
||
|
case '-':
|
||
|
op2 = -op2;
|
||
|
case '+':
|
||
|
result = op1 + op2;
|
||
|
break;
|
||
|
case '/':
|
||
|
op2 = 1 / op2;
|
||
|
case '*':
|
||
|
result = op1 * op2;
|
||
|
break;
|
||
|
}
|
||
|
stack.push(result);
|
||
|
|
||
|
} else {
|
||
|
stack.push(Number(token));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return stack.pop();
|
||
|
}
|