Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
mini_co implementation
function asyncRandom() {
return function (fn) {
setTimeout(function () {
fn(Math.random());
}, 10);
};
}
function *gen1() {
var a = yield asyncRandom();
var b = yield asyncRandom();
console.log(a, b);
}
function *gen() {
var a = yield asyncRandom();
var b = yield asyncRandom();
var c = yield asyncRandom();
var d = yield 1;
var e = yield gen1();
var f = yield gen1();
console.log(a, b, c, d);
}
function mco(generator) {
var g = generator();
(function moveNext(val) {
var next = this.next(val);
var that = this;
if (!next.done) {
var val = next.value;
if (typeof val === 'function') {
val(function (num) {
moveNext.call(that, num);
});
} else if (val.next) {
val.__done = function () {
moveNext.call(that);
};
moveNext.call(val);
} else if (typeof val === 'object' || typeof val === 'number') {
moveNext.call(that, val);
}
} else {
that.__done && that.__done();
}
}).call(g);
}
mco(gen);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment