-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150.js
More file actions
28 lines (26 loc) · 869 Bytes
/
150.js
File metadata and controls
28 lines (26 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
const isOperation = s => {
return s === "+" || s === "-" || s === "*" || s === "/";
}
const eval = (value1, value2, operation) => {
value1 = Number.parseInt(value1);
value2 = Number.parseInt(value2);
if (operation === "+") return value1 + value2;
if (operation === "-") return value1 - value2;
if (operation === "*") return value1 * value2;
if (operation === "/") return value1 / value2;
}
while(tokens.length > 0) {
if (tokens.length === 1) return Number.parseInt(tokens[0]);
const index = tokens.findIndex(isOperation) - 2;
const value1 = tokens[index];
const value2 = tokens[index + 1];
const operation = tokens[index + 2];
const value = eval(value1, value2, operation);
tokens.splice(index, 3, value);
}
};