MCPcopy Index your code
hub / github.com/TheAlgorithms/JavaScript / calcRPN

Function calcRPN

Maths/ReversePolishNotation.js:3–31  ·  view source on GitHub ↗
(expression)

Source from the content-addressed store, hash-verified

1// Wikipedia: https://en.wikipedia.org/wiki/Reverse_Polish_notation
2
3const 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
33export { calcRPN }

Callers 1

Calls 2

popMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected