Skip to content

Instantly share code, notes, and snippets.

@bmeck
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmeck/9814871 to your computer and use it in GitHub Desktop.
Save bmeck/9814871 to your computer and use it in GitHub Desktop.

These are 2 different ideas about generating output in an async manner for generators.

I may be misunderstanding the problem though.

Array based iteration

function* mappedIterator() {
  var arr = [1,1,2,3];
  var results = [];
  arr.forEach(function (item, i) {
    results[i] = 'item: ' + item;
  });
  // we have to use a separate structure to yield the values
  for (var val of results) yield val;
}

Iterator based iteration (generators in our example)

function* stuff() {
  var arr = [1,1,2,3];
  // we combinded our transform and our flow control... not awesome for reusability
  for (var val of arr) yield 'item: ' + val;
}
// refactored
function xform(item) {
  return 'item: ' + item;
}
function* stuff() {
  var arr = [1,1,2,3];
  for (var val of arr) yield xform(val);
}

Generator Comprehension equivalent

function stuff() {
  return (for (val of [1,2,3,4]) 'item: ' + val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment