Skip to content

Instantly share code, notes, and snippets.

@hdvianna
Created June 15, 2019 16:38
Show Gist options
  • Save hdvianna/a20429196f4d994a71d8634b32ecdd33 to your computer and use it in GitHub Desktop.
Save hdvianna/a20429196f4d994a71d8634b32ecdd33 to your computer and use it in GitHub Desktop.
Function chaining in javascript
function chain(c, v, f) {
if (arguments.length < 3) {
f = v; v = c; c = null;
}
var result = f.call(null, c, v);
return {
chain: chain.bind(null, result),
result: result
}
}
function add2(c, v) {
return v+2;
}
function power2(c, v) {
return Math.pow(c,v);
}
function incArray(c, v) {
return v.map(i => i+c);
}
var aChain = chain(10, add2)
.chain(2, power2)
.chain([1,2,3], incArray);
console.log(aChain.result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment