Last active
August 20, 2016 02:31
-
-
Save tonyonodi/8964b44889edeb2a4e229eebd115d7ee to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
This file contains hidden or 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
rpnCalc = (val) => { | |
const ops = { | |
"+": (a, b) => a + b, | |
"-": (a, b) => a - b, | |
"*": (a, b) => a * b, | |
"/": (a, b) => a / b, | |
}; | |
return val.split(" ") | |
.reduce((stack, val) => ( | |
parseFloat(val) ? | |
[...stack, parseFloat(val)] : | |
[...stack.slice(0, -2), ops[val].apply(null, stack.slice(-2))] | |
), [])[0]; | |
} | |
test = () => { | |
let res; | |
res = rpnCalc("5 1 2 + 4 * + 3 -"); | |
if (res !== 14) | |
console.error(res); | |
else | |
console.log(res); | |
res = rpnCalc("1 2 + 4 * 5 + 3 -"); | |
if (res !== 14) | |
console.error(res); | |
else | |
console.log(res); | |
} | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment