top | item 39648571

(no title)

AprilArcus | 2 years ago

This is a common idiom when working with generators, since iteration is controlled on the consuming side. Consider e.g. a trivial generator that counts up from one:

  function * makeSequence() {
    let i = 1;
    while (true) yield i++;
  }
This function returns an iterator:

  const ints = makeSequence();
And now the caller is control of iteration, not the callee:

  function sumTo(cutoff) {
    const ints = makeSequence();
    let sum = 0;
    for (let i = 0; i < cutoff; i++) {
      sum += ints.next().value;
    }
    return sum;
  }
In this case there is no risk of an infinite loop.

discuss

order

ramesh31|2 years ago

>This is a common idiom when working with generators, since iteration is controlled on the consuming side.

I realize that, and it's why I (and most) have avoided the syntax entirely. Generators today feel more like a vestigial appendix to the language; an aborted branch of development, than anything I'd ever use or suggest.