DEV Community

artydev
artydev

Posted on

1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay