Created
March 3, 2014 06:15
-
-
Save winsonwq/9319377 to your computer and use it in GitHub Desktop.
mini_co implementation
This file contains hidden or 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
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