DEV Community

Discussion on: Introduction to Generators in JavaScript

Collapse
 
mattkenefick profile image
Matt Kenefick

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 numbers
const numbers = Array.from(Array(20).keys())
    .sort((a, b) => Math.random() > 0.5 ? 1.0 : -1.0);

// Generator function to find odd numbers
function* oddNumberFinder(numbers) {
    for (const i of numbers) {
        if (i % 2 === 1) {
            yield i;
        }
    }
}


// Implementation
// ----------------------------------------------

let num;
const oddNumbers = oddNumberFinder(numbers);

while (num = oddNumbers.next().value) {
    console.log('Number: ' + num);
}
Enter fullscreen mode Exit fullscreen mode

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."

Collapse
 
parth2412 profile image
Parth Patil

Yup. This is a good potential use. Thanks Matt