Created
July 13, 2016 13:49
-
-
Save alvieirajr/53595e117ff291dbef02846da970361b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-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".