Created
March 1, 2012 22:05
-
-
Save nakamura-to/1953568 to your computer and use it in GitHub Desktop.
functions chain
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
function a(x) { | |
console.log('a is called: ' + x); | |
if (this.next) { | |
this.next.call(null, 'aaa'); | |
} | |
} | |
function b(x) { | |
console.log('b is called: ' + x); | |
if (this.next) { | |
this.next.call(null, 'bbb'); | |
} | |
} | |
function c(x) { | |
console.log('c is called: ' + x); | |
if (this.next) { | |
this.next.call(null, 'ccc'); | |
} | |
} | |
function d(x) { | |
console.log('d is called: ' + x); | |
if (this.next) { | |
this.next.call(null, 'ddd'); | |
} | |
} | |
function chain(functions) { | |
return functions.reduceRight(function (next, curr) { | |
return function () { | |
var context = { | |
next: next | |
}; | |
curr.apply(context, arguments); | |
} | |
}); | |
} | |
var functions = [a, b, c, d]; | |
var f = chain(functions); | |
f('hoge'); | |
console.log('done'); | |
/* RESULT | |
a is called: hoge | |
b is called: aaa | |
c is called: bbb | |
d is called: ccc | |
done | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment