Last active
January 31, 2020 15:30
-
-
Save eokoneyo/892b413bcc7d670cc32810bd4adb8520 to your computer and use it in GitHub Desktop.
Reverse Polish Notation (https://www.wikiwand.com/en/Reverse_Polish_notation)
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
const validOps = ['+', '-', '*', '/']; | |
const compute = (rightOperand, leftOperand, operation) => { | |
switch (operation) { | |
case '+': | |
return leftOperand + rightOperand; | |
case '-': | |
return leftOperand - rightOperand; | |
case '*': | |
return leftOperand * rightOperand; | |
case '/': | |
return leftOperand / rightOperand; | |
default: | |
return leftOperand; | |
} | |
} | |
const calculate = (expression) => { | |
const stack = [] | |
const evaluated = expression.split(' '); | |
evaluated.forEach(value => { | |
if (validOps.indexOf(value) < 0) { | |
if(Number.isNaN(value)) { | |
console.warn('Unsupported operand! %s was found skipping... ', value); | |
} else { | |
stack.push(Number(value)) | |
}; | |
} else { | |
stack.push(compute(stack.pop(), stack.pop(), value)); | |
} | |
}); | |
return stack.pop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment