Skip to content

Instantly share code, notes, and snippets.

@alvieirajr
Created July 13, 2016 13:49
Show Gist options
  • Save alvieirajr/53595e117ff291dbef02846da970361b to your computer and use it in GitHub Desktop.
Save alvieirajr/53595e117ff291dbef02846da970361b to your computer and use it in GitHub Desktop.
var first = (function() {
var chainNames = ["then", "andThen", "next"];
var endChainNames = ["finally", "andFinally", "last"];
var chain = function(fn) {
var f1 = function(g) {
var func = function() {return g.call(this,
fn.apply(this, arguments));};
chain(func);
return func;
};
var f2 = function(g) {
return function() {return g.call(this,
fn.apply(this, arguments));};
};
chainNames.forEach(function(name) {fn[name] = f1;});
endChainNames.forEach(function(name) {fn[name] = f2;});
};
return function(f) {
var fn = function() {
return f.apply(this, arguments);
};
chain(fn);
return fn;
};
}());
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 = first(add1).then(mult2).andThen(square).andFinally(negate);
var g = first(mult2).next(add1).then(negate).then(mult2)
.then(add1).last(square);
console.log(f(2));
console.log(g(3));
@alvieirajr
Copy link
Author

-Explicit Ordering Implementation
-This API makes a miniature DSL out of functional composition, always starting with "first", followed by any number of "then", "andThen", or "next" clauses, optionally concluding with "finally", "last", or "andFinally".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment