Skip to content

Instantly share code, notes, and snippets.

@jonathanmarvens
Last active December 26, 2015 01:19
Show Gist options
  • Save jonathanmarvens/7070205 to your computer and use it in GitHub Desktop.
Save jonathanmarvens/7070205 to your computer and use it in GitHub Desktop.
A naïve JavaScript implementation of a reverse polish calculator.
var
ReversePolish
;
ReversePolish = {};
(function (exports) {
var
operations
;
operations = {
"-": function (a, b) {
return (a - b);
},
"+": function (a, b) {
return (a + b);
}
};
function evaluate(tokens) {
var
stack
;
stack = [];
tokens.forEach(function (token) {
var
argument_1,
argument_2,
number,
operation,
result
;
if (token in operations) {
if (operations.hasOwnProperty(token)) {
argument_2 = stack.pop();
argument_1 = stack.pop();
operation = operations[token];
result = operation(argument_1, argument_2);
stack.push(result);
}
} else {
number = parseInt(token, 10);
stack.push(number);
}
});
return stack.pop();
}
exports.evaluate = evaluate;
})(ReversePolish);
var ReversePolish;ReversePolish={},function(a){function c(a){var c;return c=[],a.forEach(function(a){var d,e,f,g,h;a in b?b.hasOwnProperty(a)&&(e=c.pop(),d=c.pop(),g=b[a],h=g(d,e),c.push(h)):(f=parseInt(a,10),c.push(f))}),c.pop()}var b;b={"-":function(a,b){return a-b},"+":function(a,b){return a+b}},a.evaluate=c}(ReversePolish);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment