Last active
March 9, 2017 19:57
-
-
Save rufus2021/4a83c0cd33b279c3368fe663e300fb0b to your computer and use it in GitHub Desktop.
This file contains 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
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