Hacker News new | ask | show | jobs
by detaro 3670 days ago
Depends on what your generator does. If it just does simple calculations, just generate a second instance of it.

Otherwise there are constructions that provide a virtual copy of an iterator and cache the values they still need for the second loop.

Or just don't use an iterator if it doesn't fit the model you need, or turn it into an array before.

(Part of) the idea behind generators is that you don't store all results, because they could be a long or possibly even infinite sequence. E.g. in Python the basic iterator is range(X), which returns the numbers from 0 to X-1. If X=100000, it is a bad idea to generate a giant list of all those numbers, just because you want to know how often you ran through a loop.

1 comments

How would you copy it then? I have tried the npm deep-copy library, but that didn't work (Symbol.Iterator isn't enumerable for example)

edit: I just thought, I could make a function, bind that to a variable and regen the generator again and again

if you can easily create a new instance, that's the way to go.