Skip to content

Commit 70d871a

Browse files
authored
Reverse polish notation (TheAlgorithms#387)
* Added ReversePolishNotation * Added link to Wikipedia
1 parent a646e4b commit 70d871a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Maths/ReversePolishNotation.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Wikipedia: https://en.wikipedia.org/wiki/Reverse_Polish_notation
2+
3+
function calcRPN (expression) {
4+
const operators = {
5+
'+': (a, b) => a + b,
6+
'-': (a, b) => a - b,
7+
'*': (a, b) => a * b,
8+
'/': (a, b) => b / a
9+
}
10+
11+
const tokens = expression.split(' ')
12+
13+
const stack = []
14+
15+
tokens.forEach(token => {
16+
const operator = operators[token]
17+
18+
if (typeof operator === 'function') {
19+
const a = stack.pop()
20+
const b = stack.pop()
21+
22+
const result = operator(a, b)
23+
24+
stack.push(result)
25+
} else {
26+
stack.push(parseFloat(token))
27+
}
28+
})
29+
30+
return stack.pop()
31+
}
32+
33+
console.log(calcRPN('2 2 2 * +') === 6)
34+
console.log(calcRPN('2 2 + 2 *') === 8)
35+
console.log(calcRPN('6 9 7 + 2 / + 3 *') === 42)

0 commit comments

Comments
 (0)