Array generation (was: Pure win: Array.from and Array.of)

# David Bruant (14 years ago)

Le 10/07/2011 12:06, Dmitry A. Soshnikov a écrit :

(...)

Another thing to consider is Array.prototype.fill method which we discussed before.

The problem:

Array(4).map(function(x) x * x); // [NaN, NaN, NaN, NaN]

(by the way, this mistaken example is still mentioned in this document strawman:shorter_function_syntax, in the "Alternate Syntax Proposals" section, though, is fixed in the main section with let randomArray = NonHoleyArray(10).map(#{Math.random()}); when was mentioned before).

The solution:

// fill with a simple value

Array(4).fill(true); // [true, true, true, true]

// fill with a function in needed context of this

let object = {data: 4}; Array(3).fill(-> if this.data > 3 { 'accepted' } else {'declined' }, object);

What is Array(9).fill(function(){})? An array filled with 9 "undefined"? An array filled with 9 (no-op) functions? 9 undefined according to the implementation you provided. I think it should be 9 functions. Another syntax should be provided to generate values with a function. Maybe: Array.generate(count, fillerFunction/throws a TypeError if not callable/, thisArg) (call "count" times fillerFunction.bind(thisArg) and return value of i-th call is [[Put]] as i-th element of the array) Array.fill could be implemented as: Array.fill = function(c, v){ return Array.generate(c, (-> v) ); };

(...)

Also class-method Array.fill(count, filler) can be considered.

Since .fill seems to be intended for initialization, I would tend to be in favor of an Array.fill method rather than Array.prototype.fill. But a Array.fill syntax would prevent from choosing the prototype.

Maybe harmony:array_comprehensions could be enhanced to support array generation? Since I'm not familiar with the proposal, I won't try to play with the grammar, but it sounds like the right place to suggest initialization syntax. And it would solve the prototype issue in combination with the proto operator: myProto <| [/my syntax generating an array of 1000 elements/]