DEV Community

Discussion on: πŸ’‘πŸŽ JavaScript Visualized: Generators and Iterators

Collapse
 
lydiahallie profile image
Lydia Hallie

Your example works when we already have the all data available (to give bookclubs a value) and for datasets that aren't too big. However, we would be storing the entire bookclubs array in memory, which is something we sometimes want to avoid when working with a lot of data which might be useless.

A good example for which I often use generators is decoding a stream. In your example, we'd have to wait before we've received the entire stream before we can start decoding it (in order to give bookclubs a value). By iterating over smaller pieces of the stream, and decoding these smaller pieces, we can already start decoding it right from the beginning instead of having to wait. If you're looking for a specific piece of data that may be right at the beginning of the stream, it means that we don't have to call next again and don't have to use more memory in order to store the rest of our data, which would be useless.

(Although this is a micro-optimization which doesn't matter in most cases, I'm also not sure about performance of flatMap when working with larger, deeply nested datasets.)

Collapse
 
daviddaxi95 profile image
David Daxbacher

Ok now i got the point, makes sense. Thanks! πŸ‘

Collapse
 
tstsankov profile image
TSTsankov

const findbook = (bookID) => {
for(var i=0; i<members.length; i++)
for(var j=0; j<member[i].Books.length; j++)
if(members[i].Books[j].id == bookID)
return members[i].Books[j];
}

findbook("ey812");

Shouldn't the return statement just finish execution if/when book is found?

Thread Thread
 
iversonlv profile image
iversonLv

I think so, for loop seems the same flow with generator function for above book club example.