Here's a potential usage/implementation of a generator. This example will demonstrate how to use a generator to extract odd numbers from a list.
// Random array of numbersconstnumbers=Array.from(Array(20).keys()).sort((a,b)=>Math.random()>0.5?1.0:-1.0);// Generator function to find odd numbersfunction*oddNumberFinder(numbers){for(constiofnumbers){if(i%2===1){yieldi;}}}// Implementation// ----------------------------------------------letnum;constoddNumbers=oddNumberFinder(numbers);while(num=oddNumbers.next().value){console.log('Number: '+num);}
Here's a quote about generators from another language which could provide some context as to what they're for and why to use them:
"Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate."
I am a Parth, full stack web developer from India. I love programming and and I enjoy solving problems using software. Currently pursuing freelancing. Open to chat!
Here's a potential usage/implementation of a generator. This example will demonstrate how to use a generator to extract odd numbers from a list.
Here's a quote about generators from another language which could provide some context as to what they're for and why to use them:
"Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate."
Yup. This is a good potential use. Thanks Matt