Skip to content

Instantly share code, notes, and snippets.

@nashibao
Last active January 2, 2016 09:09
Show Gist options
  • Save nashibao/8280748 to your computer and use it in GitHub Desktop.
Save nashibao/8280748 to your computer and use it in GitHub Desktop.
minimum coroutine module (without error handling, dictionary). like https://github.com/visionmedia/co.
var co = function(fn){
function is_gen(obj) {
return obj && obj.constructor && 'GeneratorFunctionPrototype' == obj.constructor.name;
}
return function(done){
var gen = fn;
if(typeof gen == 'function')
gen = gen();
var check = function(thunk, next){
// array
if(Array.isArray(thunk)){
var res = [];
for(var i=0;i<thunk.length;i++){
check(thunk[i], function(val){
res.push(val);
if(res.length == thunk.length)
next(res);
});
}
return;
}
// generator
if(is_gen(thunk))
thunk = co(thunk);
// thunk
if(typeof thunk == 'function')
return thunk(next);
// simple object
next(thunk);
}
// next
var next = function(val){
var t = gen.next(val);
var thunk = t.value;
if(t.done){
if(done)
done(thunk);
}else{
check(thunk, next);
}
}
// start
next(undefined);
}
};
// thunk
var child = function(name){
return function(done){
setTimeout(function(){done(name);}, 500);
}
};
// nest generator
var parent = function*(name){
var val = yield child(name + '1');
console.log(" - ", val);
val = yield child(name + '2');
console.log(" - ", val);
val = yield name + '3';
console.log(" - ", val);
return name
};
// test
co(function*(){
// thunk
var val = yield child('1');
console.log(val);
// nest
var val = yield parent('2');
console.log(val);
// array
var vals = yield [child('3'), child('4')];
console.log(vals);
})();
@nashibao
Copy link
Author

nashibao commented Jan 6, 2014

node --harmony-generators co.js

output

1
 -  21
 -  22
 -  23
2
[ '3', '4' ]

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