Skip to content

Instantly share code, notes, and snippets.

@HerringtonDarkholme
Created December 24, 2013 13:06
Show Gist options
  • Save HerringtonDarkholme/8113104 to your computer and use it in GitHub Desktop.
Save HerringtonDarkholme/8113104 to your computer and use it in GitHub Desktop.
Inspired by KOA
'use strict';
// middlewares: array of generator function
function compose(middlewares) {
return function *() {
var i = middlewares.length;
var prev = function *(){};
var current;
while (i--) {
current = middlewares[i];
prev = current(prev);
}
yield *prev;
};
}
function run(gen) {
var result = gen.next();
if (result.value)
run(result.value);
// if it return, gen has no next method
if (!result.done)
gen.next();
}
var middlewares = [
function *(next) {
console.log('enter first');
yield next;
console.log('leave firt');
},
function *(next) {
console.log('enter second');
yield next;
console.log('leave second');
},
function *(next) {
console.log('enter third');
yield next;
console.log('leave third');
},
function *(next) {
console.log('end');
}
];
run(compose(middlewares)());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment