Last active
February 20, 2019 09:16
-
-
Save tomhodgins/694531561a6b839567cd96b6eae2460b 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
const builtins = [ | |
['+', (head=0, ...tail) => tail.reduce((acc, num) => acc += num, head)], | |
['-', (head=0, ...tail) => tail.reduce((acc, num) => acc -= num, head)], | |
['*', (head=0, ...tail) => tail.reduce((acc, num) => acc = acc * num, head)], | |
['/', (head=0, ...tail) => tail.reduce((acc, num) => acc = acc / num, head)], | |
['repeat', (head='', tail) => head.repeat(tail)], | |
['concat', (head, ...tail) => [head, ...tail]], | |
['join', (head, ...tail) => [...tail].join(head)] | |
] | |
builtins.forEach(([name, func]) => { | |
window[name] = func | |
}) | |
const consume = arg => | |
Array.isArray(arg) | |
? process(arg) | |
: arg | |
const process = ([func, ...args]=['+', 0, 0]) => { | |
const builtin = typeof func === 'function' ? func : window[func] | |
return builtin(...args.map(arg => consume(arg))) | |
} | |
// Addition | |
console.log( | |
process( | |
['+', 1, ['+', 2, 3]] | |
) | |
) | |
// Subtraction | |
console.log( | |
process( | |
['-', 10, 5] | |
) | |
) | |
// Multiplication | |
console.log( | |
process( | |
['*', 12, 12] | |
) | |
) | |
// Division | |
console.log( | |
process( | |
['/', 100, 50] | |
) | |
) | |
// repeat | |
console.log( | |
process( | |
[repeat, 'ha ', 3] | |
) | |
) | |
// concat | |
console.log( | |
process( | |
[concat, 'hello', 'world'] | |
) | |
) | |
// join | |
console.log( | |
process( | |
[join, ' ', 'hello', 'world'] | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment