mlhazan
mlhazan

Reputation: 1286

How to create class with collection of values using generator method in javascript/ ecmascript 6?

Here for the Service class I like to create a default iterator. I need to make service iterable but I can not think further. I believe I need to use *Symbol.iterator but don't know how to use

class Service {

  constructor() {
      this.link = [];
  }

}

var service = new Service();
service.link.push(1);
service.link.push(2);
service.link.push(3);

for (let x of service) {
  console.log(x);
}

Upvotes: 0

Views: 19

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

Yes, just define *[Symbol.iterator]() { on the class

class Service {
  constructor() {
    this.link = [];
  }
  *[Symbol.iterator]() {
    for (let i = 0; i < this.link.length; i++)
      yield this.link[i];
  }
}
var service = new Service();
service.link.push(1);
service.link.push(2);
service.link.push(3);
for (const x of service) {
  console.log(x);
}

Upvotes: 3

Related Questions