mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
32 lines
597 B
JavaScript
32 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();
|
|
}
|