Tim Hallyburton Tim Hallyburton - 1 year ago 127
Javascript Question

Create Array from Generator in JavaScript

I want to create an array from the values of an generator in JavaScript.
The generator creates a sequence of dynamic length like this

function* sequenceGenerator(minVal, maxVal) {
let currVal = minVal;

while(currVal < maxVal)
yield currVal++;

I want to store those values in an array but using
until the generator is done does not seem to be the best way possible (and looks quite ugly to be honest).

var it, curr, arr;

it = sequenceGenerator(100, 1000);
curr = it.next();
arr = [];

while(! curr.done){

Can I somehow create an array directly from/within the generator?
If not, can I somehow avoid/hide the loop? Maybe by using
or something like that?

Thanks in advance.

Answer Source

One short solution might be:

let list = [...sequenceGenerator(min, max)]

Documentation on MDN

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download