Skip to content

Instantly share code, notes, and snippets.

@CrossEye
Last active October 24, 2017 07:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CrossEye/5606668 to your computer and use it in GitHub Desktop.
Save CrossEye/5606668 to your computer and use it in GitHub Desktop.
Variadic compose by multiple calls
var compose = function compose(f) {
var queue = f ? [f] : [];
var fn = function fn(g) {
if (arguments.length) {
queue.push(g);
return fn;
}
return function() {
var args = Array.prototype.slice.call(arguments);
queue.forEach(function(func) {
args = [func.apply(this, args)];
});
return args[0];
}
};
return fn;
};
//------------------------------------------------------------------------------
var add1 = function(x) {return x + 1;};
var mult2 = function(x) {return x * 2;};
var square = function(x) {return x * x;};
var negate = function(x) {return -x;};
//------------------------------------------------------------------------------
var f = compose(add1)(mult2)(square)(negate)();
console.assert(-36, f(2), "f(2)");
@zhirzh
Copy link

zhirzh commented Jun 8, 2016

this is currying, not composing.
composing would have [psuedo] syntax like:

function compose(f, g, h) {
  return function(x) {
    return f(g(h(x)));
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment