Skip to content

Instantly share code, notes, and snippets.

@gabrieledarrigo
Created March 29, 2020 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieledarrigo/93004c7e51601626638ae7a16703e509 to your computer and use it in GitHub Desktop.
Save gabrieledarrigo/93004c7e51601626638ae7a16703e509 to your computer and use it in GitHub Desktop.
Reverse polish notation algorithm
/**
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