
Untitled
By: a guest on
Apr 17th, 2012 | syntax:
None | size: 1.07 KB | hits: 13 | expires: Never
// produce: accepts a cb which is called with an array of items
// initial: initial array of results to return
// returns a function which accepts a cb which is called with one item
// each time it is called
function generator(produce, initial) {
var items;
var waiting = [];
var next = function (cb) {
if (items && items.length) {
cb(items.shift());
if (items.length == 0) consume()
} else {
waiting.push(cb);
}
}
function consume () {
produce(function (new_items) {
items = new_items;
while (waiting.length && items && items.length) {
next(waiting.pop())
}
});
}
if (initial && initial.length) {
items = initial;
} else {
consume();
}
return next;
}
// example
var sys = require('sys');
var print = (function (s) {sys.print(s+"\n")})
var my_producer = (function () {
var i = 0;
return function (cb) {
setTimeout(function () {
cb([++i, ++i]);
}, 1000);
}
})();
var my_generator = generator(my_producer);
my_generator(print);
my_generator(print);
my_generator(print);