Last active
December 1, 2015 09:32
-
-
Save mpfund/70c70442ec9319b13006 to your computer and use it in GitHub Desktop.
mini scheme in javascript
This file contains hidden or 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
| <html> | |
| <body> | |
| <script> | |
| "use strict"; | |
| function calc(arr) { | |
| var m = arr.split(' '); | |
| return calcArr(m); | |
| } | |
| var defs = {}; | |
| function run(arr) { | |
| var op = arr[0]; | |
| var arg = arr.splice(1); | |
| if (typeof (op) === 'string') | |
| return defs[op](arg, defs, op); | |
| if (typeof (op) === 'function') | |
| return arr[0](arg, defs, op); | |
| } | |
| function runl(arr) { | |
| console.log(run(arr)); | |
| } | |
| run([function (arg, defs) { defs['='] = function (a) { defs[a[0]] = a[1] } }]); | |
| run(['=', '*', function (arg) { return arg.reduce(function (a, b) { return a * b }) }]); | |
| run(['=', '+', function (arg) { return arg.reduce(function (a, b) { return a + b }) }]); | |
| run(['=', '-', function (arg) { return arg.reduce(function (a, b) { return a - b }) }]); | |
| run(['=', 'if', function (arg) { if (arg[0] === true) { return run(arg[1]) } else { return run(arg[2]) } }]); | |
| run(['=', 'chain', function (arg) { | |
| var lastarg = run(arg[0]); | |
| for (var x = 1; x < arg.length; x++) { | |
| arg[x].push(lastarg); | |
| lastarg = run(arg[x]); | |
| } | |
| return lastarg; | |
| }]); | |
| runl(['chain', ['+', 10, 15], ['*', 2]]); | |
| runl(['if', false, ['+', 10, 20], ['-', 5, 1]]); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment