JS: Generator

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

What is generator

Generator object is a object that conforms to both the Iterable interface and Iterator interface.

it means, it is an Iterable Object and also an Iterator.

How to create generator

Write a Generator Function. it returns a generator.

or code it by hand, by creating a object with [Symbol.iterator] and "next" properties, conforming to their interfaces. This is difficult to do.

Example. write a generator manually

// create an iterator. it yields from 0 to 8.
const xiter = {};
xiter.i = 0;
xiter.next =
  () => ((xiter.i < 9)
    ? { value: xiter.i++, done: false }
    : { value: undefined, done: true });

// create a generator
const xgen = {
  // add a Symbol.iterator property, so it conforms iterable interface
  [Symbol.iterator]: (() => xiter),
  // add a next property, so it conforms iterator interface
  next: xiter.next,
};

// s------------------------------

// test it as an iterator
// call generator object by using the next() method
console.log(xgen.next());
// { value: 0, done: false }

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

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

// test it as an iterable
console.log([...xgen]);
// [ 3, 4, 5, 6, 7, 8 ]

Create generator by generator function