DEV Community

Cover image for How to add Generators methods in Class
Aman Gupta
Aman Gupta

Posted on

How to add Generators methods in Class

I wanted to write a generator function in my class and I had to do a lot of research for it. Finally found the standard way of how to write it.

Classes , Iterators_and_Generators

class Polygon {
  constructor(...sides) {
    this.sides = sides;
  }
  // Method
  *getSides() {
    for(const side of this.sides){
      yield side;
    }
  }
}

const pentagon = new Polygon(1,2,3,4,5);

console.log([...pentagon.getSides()]); // [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)