Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Last active January 3, 2021 12:35
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 jonasraoni/9bc924a6446293f0b5af3abf189d2866 to your computer and use it in GitHub Desktop.
Save jonasraoni/9bc924a6446293f0b5af3abf189d2866 to your computer and use it in GitHub Desktop.
A chained sum function in JavaScript
//+ 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