Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created December 30, 2013 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/8184121 to your computer and use it in GitHub Desktop.
Save robotlolita/8184121 to your computer and use it in GitHub Desktop.
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