-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
reverse-polish-notation-calculator.js
60 lines (52 loc) · 1.42 KB
/
reverse-polish-notation-calculator.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// for each token in the postfix expression:
// if token is an operator:
// operand_2 ← pop from the stack
// operand_1 ← pop from the stack
// result ← evaluate token with operand_1 and operand_2
// push result back onto the stack
// else if token is an operand:
// push token onto the stack
// result ← pop from the stack
// 5 1 2 + 4 * + 3 -
function calc(expr) {
const input = expr.split(' ');
const stack = [];
const operations = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
for (let i = 0; i < input.length; i++) {
const token = input[i];
if (operations[token]) {
const rightValue = stack.pop();
const leftValue = stack.pop();
const result = operations[token](+leftValue, +rightValue);
stack.push(result);
} else {
stack.push(token);
}
}
return +stack.pop();
}
function calc(expr) {
const operations = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
return +expr.split(' ').reduce((stack, token) => {
if (operations[token]) {
const rightValue = stack.pop();
const leftValue = stack.pop();
const result = operations[token](+leftValue, +rightValue);
stack.push(result);
} else {
stack.push(token);
}
return stack;
}, []).pop();
}
console.log(calc('5 1 2 + 4 * + 3 -'), 14);