i2tutorials

Javascript-Generators

Javascript-Generators

 

The generator is the new concept introduced in ES6. New way of working with iterators and functions.

This generator is a different kind of function that may be paused in the middle either one / many times and can be resumed later.

 

Javascript-Generators

 

 

Syntax:

 

// An example of generator function

 

function* gen(){
  yield 1;
  yield 2;
  ...
  ...
}

 

Example:

 

<script>// Generate Function generates an
// infinite series of Natural Numbers
function * nextNatural()
{
       var naturalNumber = 1;

       // Infinite Generation
       while (true) {
               yield naturalNumber++;
       }
}

// Calling the Generate Function
var gen = nextNatural();

// Loop to print the first
// 10 Generated number
for (var i = 0; i < 10; i++) {

        // Generating Next Number
        document.write(gen.next().value);

        // New Line
        document.write("<br>");
}
</script>

 

OUTPUT:

 

1

2

3

4

5

6

7

8

9

10

 

yield : pauses the generator execution and it returns the values of the expression which is being written after the yield keywords.

yield* :  it iterates over the operand and returns every value until done it’s true.

 

Example:

 

<script>

const arr = ['a', 'b', 'c'];

function* generator() {
yield 1;
yield* arr;
yield 2;
}

for (let value of generator()) {
document.write(value);
document.write("<br>");
}

</script>

 

OUTPUT:

 

1

a

b

c

2

 

Another method to create iterable:

 

Example:

 

<script>

var createOwnIterable = {
*[Symbol.iterator]() {
            yield 'a';
            yield 'b';
            yield 'c';
}
}

for (let value of createOwnIterable) {
document.write(value);
document.write("<br>");
}

<script>

 

OUTPUT:

 

a

b

c

 

Calling a generator from another generator:

 

Example:

 

<script>

function* firstGenerator() {
yield 2;
yield 3;
}

function* secondGenerator() {
yield 1;
yield* firstGenerator();
yield 4;
}

for (let value of secondGenerator()) {
document.write(value)
document.write("<br>");
}

</script>

 

OUTPUT:

 

1

2

3

4

 

Advantages of generators:

 

Memory efficient as lazy evaluation takes place. Delays the evaluation of an expression until its values are needed.

 

Exit mobile version