We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a646e4b commit 70d871aCopy full SHA for 70d871a
1 file changed
Maths/ReversePolishNotation.js
@@ -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