Skip to content

Instantly share code, notes, and snippets.

@CrossEye CrossEye/omega.js
Last active May 14, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.