(expression)
| 1 | // Wikipedia: https://en.wikipedia.org/wiki/Reverse_Polish_notation |
| 2 | |
| 3 | const 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 | export { calcRPN } |
no test coverage detected