Michael
Michael

Reputation: 335

Creating an multidimensional array from ES6 generator

Here is a generator creating a normal array. What is the quickest way of creating a multi dimensional array?

let seq = [...makeSequence(100)];

* makeSequence(max) {
   for (let i = 0; i < max; i++) {
     yield i;
   }
}

Upvotes: 1

Views: 688

Answers (1)

trincot
trincot

Reputation: 350137

If the iterator should return the top-level elements (which would be arrays themselves), then you could use recursion and so support any depth of array nesting:

function * makeSequence(max, dimensionCount = 1) {
   for (let i = 0; i < max; i++) {
     yield dimensionCount <= 1 ? i : [...makeSequence(max, dimensionCount-1)];
   }
}

let seq = [...makeSequence(5, 2)];

console.log(seq);

Upvotes: 1

Related Questions