mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
Reverse polish notation (#387)
* Added ReversePolishNotation * Added link to Wikipedia
This commit is contained in:
35
Maths/ReversePolishNotation.js
Normal file
35
Maths/ReversePolishNotation.js
Normal file
@ -0,0 +1,35 @@
|
||||
// Wikipedia: https://en.wikipedia.org/wiki/Reverse_Polish_notation
|
||||
|
||||
function calcRPN (expression) {
|
||||
const operators = {
|
||||
'+': (a, b) => a + b,
|
||||
'-': (a, b) => a - b,
|
||||
'*': (a, b) => a * b,
|
||||
'/': (a, b) => b / a
|
||||
}
|
||||
|
||||
const tokens = expression.split(' ')
|
||||
|
||||
const stack = []
|
||||
|
||||
tokens.forEach(token => {
|
||||
const operator = operators[token]
|
||||
|
||||
if (typeof operator === 'function') {
|
||||
const a = stack.pop()
|
||||
const b = stack.pop()
|
||||
|
||||
const result = operator(a, b)
|
||||
|
||||
stack.push(result)
|
||||
} else {
|
||||
stack.push(parseFloat(token))
|
||||
}
|
||||
})
|
||||
|
||||
return stack.pop()
|
||||
}
|
||||
|
||||
console.log(calcRPN('2 2 2 * +') === 6)
|
||||
console.log(calcRPN('2 2 + 2 *') === 8)
|
||||
console.log(calcRPN('6 9 7 + 2 / + 3 *') === 42)
|
Reference in New Issue
Block a user