Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Array from Generator in JavaScript

Tags:

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 next() 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){     arr.push(curr.value); } 

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

Thanks in advance.

like image 576
Tim Hallyburton Avatar asked Aug 11 '16 15:08

Tim Hallyburton


People also ask

How do you create a new array in JavaScript?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

How do you create an array of random values?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Are generators used in JavaScript?

Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax. When called, generator functions do not initially execute their code.


1 Answers

One short solution might be:

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

Documentation on MDN

like image 105
philipp Avatar answered Sep 24 '22 21:09

philipp