Last active
January 2, 2016 09:09
-
-
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.
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
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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output