tc39 / proposal-flatMap

proposal for flatten and flatMap on arrays
https://tc39.github.io/proposal-flatMap
214 stars 19 forks source link

What about a fillMap ? #70

Closed lifaon74 closed 6 years ago

lifaon74 commented 6 years ago

A little out of the scope, but I see frequently in js code something like this:

const array = new Array(1e5).fill(void 0).map((v, i) => { return { prop: 'test-' + i }; } );

The purpose is to fill the array with variable values, instead of fill() which only allow one value. The above code results in really non optimized initialization of array :

  1. The array is filled with non useful values (here void 0), else map or forEach won't work.
  2. The array is duplicated because of map which returns a different array.

We could have done:

const array = new Array(1e5);
for (let i = 0, l = array.length; i < l; i++) {
  array[i] = { prop: 'test-' + i };
}

But this last one is far more verbose.

It would be great to have something like array.fillMap(callback, [start, [end]]), where callback is the same as map or forEach but put data inside of array instead. The return will be the array itself. This could allow some important initialization optimization or data filling from the js engine.

The above code could be rewrite as:

const array = new Array(1e5).fillMap((v, i) => { return { prop: 'test-' + i }; } );

Finally, the fillMap is just an idea, others names could be used.

Let me know what you think !

ljharb commented 6 years ago

This is already better done with Array.from({ length: 1e5 }, (_, i) => { … })

lifaon74 commented 6 years ago

Nice solution. I didn't expect providing an object with a length property to Array.from() will create an empty array.