Skip to content

Instantly share code, notes, and snippets.

@devm33
Created May 14, 2014 04:31
Show Gist options
  • Save devm33/b3120655764eed834e64 to your computer and use it in GitHub Desktop.
Save devm33/b3120655764eed834e64 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
function calc(expr) {
return expr.split(/\s+/).reduce(function(stack, current){
var a, b, c;
if(/[+\-*\/]/.test(current)){
b = stack.pop();
a = stack.pop();
switch(current) {
case '+': c = a + b; break;
case '-': c = a - b; break;
case '*': c = a * b; break;
case '/': c = a / b; break;
}
} else {
c = parseFloat(current);
}
stack.push(c);
return stack;
}, []).pop() || 0; // readability: low, fun: high
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment