Created
March 29, 2020 11:18
-
-
Save gabrieledarrigo/93004c7e51601626638ae7a16703e509 to your computer and use it in GitHub Desktop.
Reverse polish notation algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Author's note: This is the algorithm taken from https://en.wikipedia.org/wiki/Reverse_Polish_notation | |
for each token in the postfix expression: | |
if token is an operator: | |
operand_2 ← pop from the stack | |
operand_1 ← pop from the stack | |
result ← evaluate token with operand_1 and operand_2 | |
push result back onto the stack | |
else if token is an operand: | |
push token onto the stack | |
result ← pop from the stack | |
*/ | |
function calculate(expression) { | |
if (expression === '') { | |
return ''; | |
} | |
const stack = []; | |
const tokens = expression.split(' '); | |
const operators = ['+', '-', '*', '/']; | |
tokens.forEach((t, i) => { | |
const operator = operators.find((o) => o === t); | |
if (operator) { | |
const first = stack.pop(); | |
const second = stack.pop(); | |
const result = `${second} ${operator} ${first}`; | |
stack.push(eval(result)); | |
} else { | |
stack.push(t); | |
} | |
}); | |
return stack.pop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment