Last active
January 3, 2021 12:35
-
-
Save jonasraoni/9bc924a6446293f0b5af3abf189d2866 to your computer and use it in GitHub Desktop.
A chained sum function in JavaScript
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
//+ Jonas Raoni Soares Silva | |
//@ http://raoni.org | |
// Iteration 3: manually minified xD | |
const sum = (...args) => ((v, r = sum.bind(this, v)) => (r[Symbol.toPrimitive] = () => v, r))(args.reduce((a, b) => a + b, 0)); | |
// Iteration 2: supports sum(1,2,3) | |
const sum = (...args) => { | |
const operation = (...args) => args.reduce((a, b) => a + b, 0); | |
let current = operation(...args); | |
const chain = (...args) => (current = operation(current, ...args), chain); | |
chain[Symbol.toPrimitive] = () => current; | |
return chain; | |
}; | |
// Iteration 1 | |
const sum = (current) => { | |
const chain = (...v) => { | |
current = [].reduce.call(v, (a, b) => a + b, current); | |
return chain; | |
}; | |
chain[Symbol.toPrimitive] = () => current; | |
return chain; | |
}; | |
// Alternative implementation with a Proxy | |
const sum = (...args) => { | |
const proxy = new Proxy((...args) => args.reduce((a, b) => a + b), { | |
value: 0, | |
get () { | |
return () => this.value; | |
}, | |
apply (target, _, args) { | |
this.value = target(this.value, ...args); | |
return proxy; | |
} | |
}); | |
return proxy(...args); | |
}; | |
sum(1,2)(3)(4)(5,6); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment