File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments