DEV Community

artydev
artydev

Posted on

Extending generators with a toArray method.

Generators miss a toArray method.

Here is an implementation:


Object.defineProperty(
 Object.getPrototypeOf(function* () {}).prototype,
 "toArray",
 {
   value: function () { return Array.from(this) }
 }
);

Enter fullscreen mode Exit fullscreen mode

Here a use case :



Object.defineProperty(
 Object.getPrototypeOf(function* () {}).prototype,
 "toArray",
 {
   value: function () { return Array.from(this) }
 }
);

function* range (start , end ) {
  while (start <= end) {
    yield start++
  }
}

let r10to20 = range(10, 20).toArray()

console.log(r10to20)  // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]

Enter fullscreen mode Exit fullscreen mode

You can play with the demo here DEMO

Top comments (0)