-
-
Save hiun/24332088288f2869cd3c7cd00ed40959 to your computer and use it in GitHub Desktop.
Functional compostion using fake operator overloading
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
// Based on a discussion with Michael Haufe: | |
// https://groups.google.com/group/jsmentors/browse_thread/thread/d028fb0041f93a27 | |
// Not really recommended for anything but the fun of knowing it can be done! | |
var omega = function() { | |
var queue = []; | |
var valueOf = Function.prototype.valueOf; | |
Function.prototype.valueOf = function() { | |
queue.push(this); | |
return 1; // not needed now, but could be used later to distinguish operators. | |
}; | |
return function() { | |
Function.prototype.valueOf = valueOf; | |
return function(x) { | |
for (var i = 0, val = x, len = queue.length; i < len; i++) { | |
val = queue[i](val); | |
} | |
return val; | |
} | |
}; | |
}; |
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 = omega()(add1 >> mult2 >> square >> negate); | |
var g = omega()(mult2 >> add1 >> negate >> square >> add1); | |
var h = omega()(f >> g >> add1); | |
console.assert(-36 == f(2), "f(2)"); | |
console.assert(-64 == f(3), "f(3)"); | |
console.assert(50 == g(3), "g(3)"); | |
console.assert(963 == h(1), "h(1)"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment