Created
May 14, 2014 04:31
-
-
Save devm33/b3120655764eed834e64 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
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