Evaluate Reverse Polish Notation LeetCode solution in JavaScript

1
const ops = new Set(["+", "-", "*", "/"]);
2

3
/**
4
* @param {string[]} tokens
5
* @return {number}
6
*/
7
var evalRPN = function (tokens) {
8
const stack = [];
9

10
for (const token of tokens) {
11
if (!ops.has(token)) {
12
stack.push(Number(token));
13
continue;
14
}
15

16
const val1 = stack.pop();
17
const val2 = stack.pop();
18
let toPush;
19

20
if (token === "+") {
21
toPush = val1 + val2;
22
}
23

24
if (token === "-") {
25
toPush = val2 - val1;
26
}
27

28
if (token === "*") {
29
toPush = val1 * val2;
30
}
31

32
if (token === "/") {
33
toPush = Math.trunc(val2 / val1);
34
}
35

36
stack.push(toPush);
37
}
38

39
return stack[0] || 0;
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0