Skip to content

Instantly share code, notes, and snippets.

@tonyonodi
Last active August 20, 2016 02:31
Show Gist options
  • Save tonyonodi/8964b44889edeb2a4e229eebd115d7ee to your computer and use it in GitHub Desktop.
Save tonyonodi/8964b44889edeb2a4e229eebd115d7ee to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
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