Skip to content

Instantly share code, notes, and snippets.

@alvieirajr
Last active July 13, 2016 13:28
Show Gist options
  • Save alvieirajr/46548e5e6e3a9bae0646cd1dbc0f1fcd to your computer and use it in GitHub Desktop.
Save alvieirajr/46548e5e6e3a9bae0646cd1dbc0f1fcd to your computer and use it in GitHub Desktop.
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)();
console.log(f(2));
f = compose(add1)(mult2)();
console.log(f(2));
f = compose(add1)(mult2)(square)();
console.log(f(2));
f = compose(add1)(mult2)(square)(negate)();
console.log(f(2));
@alvieirajr
Copy link
Author

The functions can be read from left-to-right:

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