Last active
June 16, 2016 08:48
-
-
Save CrossEye/5606649 to your computer and use it in GitHub Desktop.
Prototype composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//------------------------------------------------------------------------------ | |
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