Skip to content

Instantly share code, notes, and snippets.

@stoeffel
Created February 13, 2015 13:51
Show Gist options
  • Select an option

  • Save stoeffel/8d230cdbaf37393cd688 to your computer and use it in GitHub Desktop.

Select an option

Save stoeffel/8d230cdbaf37393cd688 to your computer and use it in GitHub Desktop.
function compose2(fn1, fn2) {
return (...args) => fn1(fn2.apply(null, args));
}
function compose(...fns) {
let head = fns.shift();
let tail = fns;
if (head && tail.length === 0) {
return head;
}
if (tail.length === 1) {
return compose2(head, tail[0]);
}
return compose2(head, compose.apply(null, tail));
}
function add2(x) {
return x + 2;
}
function sqr(x) {
return x * x;
}
var l = console.log;
l(
compose(sqr)(2)
);
l(
compose(sqr, add2)(2)
);
l(
compose(sqr, add2, add2)(2)
);
l(
compose(sqr, add2, add2, add2)(2)
);
l(
compose(sqr, add2, add2, add2, add2)(2)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment