How Does The Next () Function Work With Generators?

Asked 5 months ago
Answer 1
Viewed 469
1

The following() technique for Generator examples returns an article with two properties done and esteem. You can likewise give a boundary to the following technique to send a worth to the generator.

Syntax

next()
next(value)

Parameters

The value to send to the generator.

The worth will be relegated because of a yield articulation. For instance, in factor = yield articulation, the worth passed to the .following() capability will be relegated to variable.

Return value

An Object with two properties:

done
A boolean worth:

valid assuming the generator is past the finish of its control stream. For this situation esteem indicates the return worth of the generator (which might be indistinct).
bogus assuming the generator can create more qualities.

Any JavaScript value yielded or returned by the generator.

Models
Utilizing straightaway()
The accompanying model shows a basic generator and the item that the following technique returns:

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

const g = gen(); // Generator { }
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: 3, done: false }
g.next(); // { value: undefined, done: true }

Using next() with a list

function* getPage(list, pageSize = 1) {
  for (let index = 0; index < list.length; index += pageSize) {
    yield list.slice(index, index + pageSize);
  }
}

const list = [1, 2, 3, 4, 5, 6, 7, 8];
const page = getPage(list, 3); // Generator { }

page.next(); // { value: [1, 2, 3], done: false }
page.next(); // { value: [4, 5, 6], done: false }
page.next(); // { value: [7, 8], done: false }
page.next(); // { value: undefined, done: true }

Sending values to the generator

 

function* gen() {
  while (true) {
    const value = yield;
    console.log(value);
  }
}

const g = gen();
g.next(1); // Returns { value: undefined, done: false }
// No log at this step: the first value sent through `next` is lost
g.next(2); // Returns { value: undefined, done: false }
// Logs 2

Answered 5 months ago Pirkko Koskitalo