Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 17th, 2012  |  syntax: None  |  size: 1.07 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // produce: accepts a cb which is called with an array of items
  2. // initial: initial array of results to return
  3. // returns a function which accepts a cb which is called with one item
  4. // each time it is called
  5. function generator(produce, initial) {
  6.   var items;
  7.   var waiting = [];
  8.  
  9.   var next = function (cb) {
  10.     if (items && items.length) {
  11.       cb(items.shift());
  12.       if (items.length == 0) consume()
  13.     } else {
  14.       waiting.push(cb);
  15.     }
  16.   }
  17.  
  18.   function consume () {
  19.     produce(function (new_items) {
  20.       items = new_items;
  21.       while (waiting.length && items && items.length) {
  22.         next(waiting.pop())
  23.       }
  24.     });
  25.   }
  26.  
  27.   if (initial && initial.length) {
  28.     items = initial;
  29.   } else {
  30.     consume();
  31.   }
  32.  
  33.   return next;
  34. }
  35.  
  36. // example
  37. var sys = require('sys');
  38. var print = (function (s) {sys.print(s+"\n")})
  39.  
  40. var my_producer = (function () {
  41.   var i = 0;
  42.   return function (cb) {
  43.     setTimeout(function () {
  44.       cb([++i, ++i]);
  45.     }, 1000);
  46.   }
  47. })();
  48.  
  49. var my_generator = generator(my_producer);
  50.  
  51. my_generator(print);
  52. my_generator(print);
  53. my_generator(print);