Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active February 20, 2019 09:16
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 tomhodgins/694531561a6b839567cd96b6eae2460b to your computer and use it in GitHub Desktop.
Save tomhodgins/694531561a6b839567cd96b6eae2460b to your computer and use it in GitHub Desktop.
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