Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.