Take a limited number of items from a potentially infinite generator Hypothetically, I have a bunch of generators that never end, like:


function* progression() {
  let n = 0;

  while (true) {
    yield n++;
  }
}



I want to take first N items from that generator. So I made a function take for that:

function* take(n, generator) {
  let i = 0;
  let values = generator();

  for (let v of values) {
    if (++i &gt; n) {
      return;
    }

    yield v;
  }
}


Is there a better way, maybe standard ES6+ API or a more concise syntax to achieve the same thing? If this function could fail under circumstances that I didn't account for, please give me a hint.
I would write it as:

function* take(n, generator) {
  let values = generator();

  let i = 0;
  while (i++ &lt; n) {
    yield values.next().value;
  }
}


this seems to match the intent more closely though its mostly a matter of personal preference.

Update

You can also add the take method as an extension to the generator so you could call it like generator().take(3). See this SO answer if you are interested in that approach.