Javascript - Collection Generator Function

Introduction

A generator function is paused by executing a yield keyword in the body of the function.

You can return a value from a yield expression.

The following example yields the value 42 from a generator:

function *generator () { 
    yield 42; 
} 

You can pass arguments to a Generator.

Executing a generator produces an iterator that can be used to execute the code inside it.

Consider the following code

function *gen() { 
    yield "Hello"; 
    yield "from"; 
    yield "generator"; 
} 

If we call this generator function, it will returns an iterator that will be used to execute the code inside it.

let obj = gen(); 

The method obj.next() continues the execution of gen, until the next yield expression:

console.log(obj.next());   // { value: "Hello", done: false} 
console.log(obj.next());   // { value: "from",  done: false} 
console.log(obj.next());   // { value: "generator", done: false} 
console.log(obj.next());   // { value: undefined, done: true} 

yield can be used any number of times inside a generator.

It can be a part of a loop.

function *infiniteNumbers() { 
    var n = 1; 
    while (true) { 
        yield n++; 
    } 
} 
var numbers = infiniteNumbers(); // returns an iterable object 

console.log(numbers.next()); // { value: 1, done: false } 
console.log(numbers.next()); // { value: 2, done: false } 
console.log(numbers.next()); // { value: 3, done: false } 

A yield statement without a value provided just implies that the value is undefined.

Related Topic