Skip to content

Instantly share code, notes, and snippets.

@rufus2021
Last active March 9, 2017 19:57
Show Gist options
  • Save rufus2021/4a83c0cd33b279c3368fe663e300fb0b to your computer and use it in GitHub Desktop.
Save rufus2021/4a83c0cd33b279c3368fe663e300fb0b to your computer and use it in GitHub Desktop.
var operators = ['+', '-', '*', '/'];
var string = '4 2 + 3 5 1 - * +';
var funcs = {
'+': function (a, b) {
return b + a;
},
'-': function (a, b) {
return b - a;
},
'*': function (a, b) {
return b * a;
},
'/': function (a, b) {
return b / a;
}
}
function postfix (str) {
var len = str.length;
var stack = [];
for (var i = 0; i <= str.length; i++) {
var token = str.charAt(i);
var isNumber = parseInt(token);
var isOperator = operators.indexOf(token) !== -1;
if (isNumber) {
stack.push(parseInt(token));
}
if (isOperator) {
var a = Number(stack.pop());
var b = Number(stack.pop());
var result = funcs[token](a, b);
stack.push(result);
}
}
return stack;
}
postfix(string);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment