Array.massMake()

Right now, when you have to make an array of identical values of some size, there are a few ways to do it:

'use strict';
const arr = [];
for (let idx = 0; idx < 32; idx++) {
  arr[idx] = 0;
}

this approach is a little better:

'use strict';
const len = 32;
const arr = new Array(len);
for (let idx = 0; idx < len; idx++) {
  arr[idx] = 0;
}

In most cases, we have to iterate through each entry in the array and manually set it, even if the entries within the array all have identical values at their initial setting.

I’m proposing that, in addition to allowing the current approaches, we add Array.massMake(), which could work like this:

'use strict';
const len = 32;
const allInitialValues = 0;
const arr = Array.massMake(len, allInitialValues);

This would simplify and reduce code. There might be some performance improvements resulting from this, but that would depend on the implementation from the runtime engine. I’m merely proposing this for the code reduction and simplification.

Also, if someone has a better name than Array.massMake(), please note it in the comments.

You can do it in two steps today like this:

new Array(5).fill(42)

This creates an array of size 5 where each item has the number 42.

Using new Array() does technically create an array with holes, which is generally seen as a bad thing, but those holes are immediately plugged with .fill(). Still, if you want to avoid it, this works too:

Array.from({ length: 5 }, () => 42)

The use of a callback makes this pattern work for objects, not just primitives. (If you use .fill() to fill an array with an object, each item in the array would point to the same object reference which is generally not wanted, but if you use a callback to generate an object at each step, each array entry would have a unique object reference).

3 Likes

It’s not an identical interface, but I suppose that works for this issue. I guess this should be marked as closed.