Created
December 30, 2013 16:15
-
-
Save robotlolita/8184121 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
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