1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 19:19:07 +01:00
CodeWars/6kyu/rpn_calculator/solution.js

33 lines
597 B
JavaScript
Raw Normal View History

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