Created
January 27, 2010 14:22
-
-
Save adamse/287864 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 functions = { | |
"+": { | |
argc: 2, | |
func: function (a, b) { | |
return a + b | |
} | |
}, | |
"-": { | |
argc: 2, | |
func: function (a, b) { | |
return a - b | |
} | |
}, | |
"*": { | |
argc: 2, | |
func: function (a, b) { | |
return a * b | |
} | |
}, | |
"/": { | |
argc: 2, | |
func: function (a, b) { | |
return a / b | |
} | |
}, | |
"**": { | |
argc: 2, | |
func: function (a, b) { | |
return Math.pow(a, b) | |
} | |
} | |
} | |
function execute (input, funcs) { | |
return input.reduce( | |
function (stack, curr) { | |
if (curr in funcs) { | |
return stack.concat( | |
funcs[curr].func.apply( | |
this, | |
stack.splice(-(funcs[curr].argc), funcs[curr].argc) | |
) | |
) | |
} else { | |
return stack.concat(curr) | |
} | |
}, | |
[] | |
) | |
} | |
function compile (stack, functions) { | |
stack = stack.reduce( | |
function (acc, curr) { | |
if (curr === "defun") { | |
var name = acc.pop(), | |
argc = acc.pop(), | |
funcCount = acc.pop(), | |
funcs = acc.splice(-funcCount, funcCount); | |
functions[name] = { | |
argc: argc, | |
func: function () { | |
return run(Array.prototype.slice.call(arguments).concat(funcs)) | |
} | |
} | |
return acc; | |
} else { | |
return acc.concat(curr) | |
} | |
}, | |
[] | |
); | |
return [stack, functions]; | |
} | |
function run (str) { | |
return execute.apply( | |
this, | |
compile(str, functions) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment