Last active
December 17, 2015 10:18
-
-
Save icholy/5593188 to your computer and use it in GitHub Desktop.
generator idea
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
var generator = function (fn) { | |
var next_callback = null, | |
yield_callback = null, | |
yield_value = null; | |
var reset = function () { | |
next_callback = null; | |
yield_callback = null; | |
yield_value = null; | |
} | |
var next = function (cb) { | |
if (yield_callback !== null) { | |
var v = yield_value, | |
c = yield_callback; | |
reset(); c(); cb(); | |
} else { | |
next_callback = cb; | |
} | |
}; | |
var yield = function (val, cb) { | |
if (next_callback !== null) { | |
var c = next_callback; | |
reset(); c(val); cb(); | |
} else { | |
yield_callback = cb; | |
yield_value = val; | |
} | |
}; | |
fn(yield); | |
return { next: next }; | |
}; | |
var loop = function (fn) { | |
var recur = function () { fn(next); } | |
var next = function () { setTimeout(recur, 0); }; | |
recur(); | |
} | |
var g = generator(function (yield) { | |
var count = 0; | |
loop(function (next) { | |
count++; | |
setTimeout(function () { | |
yield(123, next); | |
}, count * 100); | |
}); | |
}); | |
loop(function (next) { | |
g.next(function (val) { | |
console.log(val); | |
next(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment