Last active
October 2, 2018 11:38
-
-
Save jonniek/e401fb5df6bb6e4657e290153bf34fdf to your computer and use it in GitHub Desktop.
Postfix calculator
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
function Stack() { | |
let arr = [] | |
return { | |
push: (data) => arr.push(data), | |
pop: () => arr.pop(), | |
show: () => arr | |
} | |
} | |
function calc(string, showstack) { | |
let stack = Stack() | |
let inputs = string.split(" ") | |
inputs.forEach(char => { | |
if (!["+","-","*","/","%"].includes(char)) { | |
stack.push(char) | |
if (showstack) console.log(stack.show()) | |
} else { | |
const value1 = stack.pop() | |
const value2 = stack.pop() | |
const expr = value2 + char + value1 | |
const value = eval(expr) | |
stack.push(value) | |
if (showstack) console.log(stack.show()) | |
} | |
}) | |
return stack.pop() | |
} | |
calc("3 4 + 5 2 / *", true) | |
calc("3 4 - 5 2 / *") | |
calc("11 5 %") | |
calc("2 2 * 2 2 * *") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment