Skip to content

Instantly share code, notes, and snippets.

@hiun
Forked from CrossEye/omega.js
Created June 27, 2017 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiun/24332088288f2869cd3c7cd00ed40959 to your computer and use it in GitHub Desktop.
Save hiun/24332088288f2869cd3c7cd00ed40959 to your computer and use it in GitHub Desktop.
Functional compostion using fake operator overloading
// 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;
}
};
};
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