Skip to content

Commit fc1ac34

Browse files
committedJun 10, 2022
Fixed formatting and performance for JS problem 150
1 parent 96f2788 commit fc1ac34

File tree

1 file changed

+21
-25
lines changed

1 file changed

+21
-25
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
1+
/** @const {!Object} */
2+
const OPERATORS = {
3+
'+': (a, b) => a + b,
4+
'-': (a, b) => a - b,
5+
'*': (a, b) => a * b,
6+
'/': (a, b) => Math.trunc(a / b)
7+
};
8+
19
/**
210
* @param {string[]} tokens
311
* @return {number}
412
*/
5-
var evalRPN = function(tokens) {
6-
let stack = [];
7-
for (const token of tokens) {
8-
if (/^[+\-*\/]$/.test(token)) {
9-
const rhs = stack.pop();
10-
const lhs = stack.pop();
11-
switch (token) {
12-
case '+':
13-
stack.push(lhs+rhs);
14-
break;
15-
case '-':
16-
stack.push(lhs-rhs);
17-
break;
18-
case '*':
19-
stack.push(lhs*rhs);
20-
break;
21-
case '/':
22-
stack.push(Math.trunc(lhs/rhs));
23-
};
24-
} else {
25-
stack.push(Number(token));
26-
};
27-
};
28-
return stack.pop();
29-
};
13+
function evalRPN(tokens) {
14+
const stack = [];
15+
for (const token of tokens) {
16+
if (token in OPERATORS) {
17+
const rhs = stack.pop();
18+
const lhs = stack.pop();
19+
stack.push(OPERATORS[token](lhs, rhs));
20+
} else {
21+
stack.push(Number(token));
22+
}
23+
}
24+
return stack.pop();
25+
}

0 commit comments

Comments
 (0)
Please sign in to comment.