Skip to content

Instantly share code, notes, and snippets.

@riston
Last active August 29, 2015 14:06
Show Gist options
  • Save riston/3bf936b41409ad0deb2a to your computer and use it in GitHub Desktop.
Save riston/3bf936b41409ad0deb2a to your computer and use it in GitHub Desktop.
reverse polish stack
var isOp = function (op) {
return !!({
'+': true,
'-': true,
'*': true,
'/': true
}[op])
};
var applyOp = function (op, a, b) {
return ({
'+': a + b,
'-': b - a,
'*': a * b,
'/': b / a
})[op];
};
function calc(expr) {
var input = expr.split(' '),
len = input.length,
stack = [],
cell;
if (len <= 0) {
return 0;
}
while (input.length > 0) {
cell = input.shift();
if (!isOp(cell)) {
stack.push(+cell);
}
else {
input.unshift(applyOp(cell, stack.pop(), stack.pop()));
}
}
return stack.pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment