Reputation: 335
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
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