How to make an iterator out of an ES6 class How to make an iterator out of an ES6 class javascript javascript

How to make an iterator out of an ES6 class


You need to specify Symbol.iterator property for SomeClass which returns iterator for class instances. Iterator must have next() method, witch in turn returns object with done and value fields. Simplified example:

function SomeClass() {  this._data = [1,2,3,4];}SomeClass.prototype[Symbol.iterator] = function() {  var index = 0;  var data  = this._data;  return {    next: function() {      return { value: data[++index], done: !(index in data) }    }  };};

Or using ES6 classes and arrow functions:

class SomeClass {  constructor() {    this._data = [1,2,3,4];  }  [Symbol.iterator]() {    var index = -1;    var data  = this._data;    return {      next: () => ({ value: data[++index], done: !(index in data) })    };  };}

And usage:

var obj = new SomeClass();for (var i of obj) { console.log(i) }

In your updated question you realized class iterator through generator function. You can do so, but you must understand that iterator COULD NOT BE a generator. Actually iterator in es6 is any object that has specific next() method


Define a suitable iterator method. For example:

class C {  constructor() { this.a = [] }  add(x) { this.a.push(x) }  [Symbol.iterator]() { return this.a.values() }}

Edit: Sample use:

let c = new Cc.add(1); c.add(2)for (let i of c) console.log(i)


Here's an example for iterating over a 2d matrix custom class in ES6

class Matrix {    constructor() {        this.matrix = [[1, 2, 9],                       [5, 3, 8],                       [4, 6, 7]];    }    *[Symbol.iterator]() {        for (let row of this.matrix) {            for (let cell of row) {                yield cell;            }        }    }}

The usage of such a class would be

let matrix = new Matrix();for (let cell of matrix) {    console.log(cell)}

Which would output

129538467