Skip to content

Instantly share code, notes, and snippets.

@CrossEye
Last active June 16, 2016 08:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrossEye/5606649 to your computer and use it in GitHub Desktop.
Save CrossEye/5606649 to your computer and use it in GitHub Desktop.
Prototype composition
Function.prototype.compose = function(g) {
var fn = this;
return function() {
return fn.call(this, g.apply(this, arguments));
};
};
Function.prototype.pipe = function(g) {
var fn = this;
return function() {
return g.call(this, fn.apply(this, arguments));
};
};
//------------------------------------------------------------------------------
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 = negate.compose(square).compose(mult2).compose(add1);
console.assert(-36, f(2), "f(2)");
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
var g = add1.pipe(mult2).pipe(square).pipe(negate);
console.assert(-36, g(2), "g(2)");
//------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment