Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function evaluate(ast){
return ast.reduce(function(result, a){ return compute(a, result) }, [])
}
function parse(input){
return input.trim().split(/\s+/)
}
function compute(a, stack) {
return a === '+'? concat(stack, pop(stack) + pop(stack))
: a === '*'? concat(stack, pop(stack) * pop(stack))
: a === '-'? concat(stack, pop(stack) - pop(stack))
: a === '/'? concat(stack, pop(stack) / pop(stack))
: stack.concat([a])
}
function concat(stack, value){
return stack.concat(value)
}
function pop(stack) {
if (stack.length === 0) throw new Error("Not enough parameters")
return Number(stack.pop())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment