Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created March 1, 2012 22:05
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 nakamura-to/1953568 to your computer and use it in GitHub Desktop.
Save nakamura-to/1953568 to your computer and use it in GitHub Desktop.
functions chain
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