(no title)
AprilArcus | 2 years ago
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.
ramesh31|2 years ago
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.