As best I can tell that isn't possible. Per this useful wiki and the draft version of ES6 on generators, once you've returned from it (rather than yielded), it puts it into the "closed"
state and there is no way to move it back to the "newborn"
state which is how a new generator starts out.
You may have to pass along a callback to your other scope for creating a new generator. As a work-around, you could even add that callback as a custom method on the generator you sent to the other scope if you wanted and that callback would create a new generator for the other scope.
If you think about how generators work, they'd have to execute over from scratch to reset their initial state and there's simply no reason to support that. That would be analagous to asking why you can't just re-execute the constructor on an existing object and expect to have a virgin object in the same object. While it's all technically doable, it's hairy to make work right and there's really no reason to support it. If you want a virgin object, just create a new one. Same with a generator.
This is a bit of a hack, but a curious thing to contemplate. You could make a generator that repeated itself. Suppose your generator worked like this:
var generator = function*() {
while (true) {
yield 1;
yield 2;
yield 3;
yield null;
}
};
var iterable = generator();
for (let x of iterable) {
if (x === null) break;
console.log(x);
}
// generator is now in a state ready to repeat again
I can easily see how this might be an anti-pattern though because if you ever do this:
for (let x of iterable) {
console.log(x);
}
You will have an infinite loop, so it would have to be used with great care. FYI, the above wiki shows examples of an infinite Fibonacci sequence so an infinite generator is certainly contemplated.
for (let x in iterable)
befor (let x of iterable)
? – Hyperventilationfor (let val of iterable) {}
. I ended up making my own wrapper class that hadSymbol.iterator
defined on it, which would automatically expand any wrapped generators (that didn't require any arguments, anyways) before attempting an iteration. It worked fine. Treating generators as lazy loading sequences of data wasn't great as far as performance goes, though. – Fourinhand