Saturday, 22 December 2018

Explain about Generators in JavaScript

Generators are used to define an iterative algorithm by writing a single function whose execution is not continuous.

How to define a generator?
'function*' declaration used to define a generator function.

Example
function* nextEvenNumber() {
  yield 2;
  yield 4;
  yield 6;
  yield 8;
}

HelloWorld.js
function* nextEvenNumber() {
  yield 2;
  yield 4;
  yield 6;
  yield 8;
}

var evenNumbers = nextEvenNumber();

console.log(evenNumbers.next());  // Get first yied, 2
console.log(evenNumbers.next());  // Get second yied, 4
console.log(evenNumbers.next());  // Get third yied, 6
console.log(evenNumbers.next());  // Get fourth yied, 8
console.log(evenNumbers.next());  // Get fifth yied, which is not there, undefined
console.log(evenNumbers.next());  // Get sixth yied, which is not there, undefined

Output
Object { value: 2, done: false }
Object { value: 4, done: false }
Object { value: 6, done: false }
Object { value: 8, done: false }
Object { value: undefined, done: true }
Object { value: undefined, done: true }

evenNumbers.next()
Returns a value yielded by the yield expression.

As you see the output, 'evenNumbers.next()' method returns an object that contains a value and a flag 'done'. Flag 'done' set to false, if next yield expression is available, else false.

Let’s enhance the above function to return infinite even numbers.

HelloWorld.js
function* nextEvenNumber() {
  var i = 0;
  
  while(true){
    yield i;
    i += 2;
  }
}

var evenNumbers = nextEvenNumber();

/* Print first 10 even numbers */
for(var i=0; i < 10; i++){
  console.log(evenNumbers.next().value);
}

Output
0
2
4
6
8
10
12
14
16
18

Can a generator function take arguments?
Yes, a generator function takes arguments.

function* name(param1, param2....paramN) {
   statements
}


HelloWorld.js
function* nextEvenNumber(maxNumber) {
  var i = 0;
  
  while(i <= maxNumber){
    yield i;
    i += 2;
  }
}

var evenNumbers = nextEvenNumber(10);

var obj = evenNumbers.next();

while(!obj.done){
  console.log(obj.value);
  obj = evenNumbers.next();
}

Output
0
2
4
6
8
10


Previous                                                 Next                                                 Home

No comments:

Post a Comment