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.
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.
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.
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.
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.
One short solution might be:
let list = [...sequenceGenerator(min, max)]
Documentation on MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With