Or for that matter, similarly....  Array.fill(), which has the same
signature, but an empty array as Array.prototype.fill.

-- 
Michael J. Ryan - http://tracker1.info


On Tue, Mar 27, 2018 at 5:24 PM Michael J. Ryan <[email protected]> wrote:

> How about something like...
>
> Array.prototype.fill = function(filler, times, flatten) {
>   var ret = [].concat(this);
>   var len = Number(times) || 0;
>   var (var i=0; i<len; i++) {
>     if (flatten && Array.isArray(filler)) {
>       ret.push.apply(ret, filler);
>     } else {
>       ret.push(filler);
>     }
>   }
>   return ret;
> }
>
> [].fill(0, 3) // [0, 0, 0]
> [].fill(['a', 'b'], 2) // [['a', 'b'], ['a', 'b']]
> [].fill(['a', 'b'], 2, true) // ['a', 'b', 'a', 'b']
>
> --
> Michael J. Ryan - http://tracker1.info
>
>
> On Mon, Mar 26, 2018 at 12:02 PM Cyril Auburtin <[email protected]>
> wrote:
>
>> > maybe fill with incrementing number?
>>
>> ```js
>> Array.from({length: 6}, (_, i) => i)
>> ```
>>
>> > Are there use cases for filling with alternating values, as in `['x',
>> 'y'].repeat(3)`?
>>
>> Not so many, but for example when working with flat matrices,
>> `[0,0,255,1].repeat(len)` for generating quickly a uniform imageData
>>
>> But even with one item, I find `[x].repeat(n)` more explicit than the 2
>> other alternatiives
>>
>> It's somewhat close to array comprehensions (that I don't really miss
>> though)
>>
>>
>> 2018-03-26 15:27 GMT+02:00 Jerry Schulteis <[email protected]>:
>>
>>> Whatever the use cases might be, I like generators and spread for
>>> filling an array with values, e.g.:
>>>
>>> ```js
>>> function* repeat(n, ...values) {
>>>   for (let i = 0; i < n; ++i) {
>>>     yield* values;
>>>   }
>>> }
>>>
>>> [...repeat(3, 'x', 'y')]
>>> ```
>>>
>>>
>>> On Sunday, March 25, 2018, 3:41:10 PM CDT, Claude Pache <
>>> [email protected]> wrote:
>>>
>>>
>>> [...]
>>>
>>> For filling a new array with one value, `Array(n).fill('foo')` seems
>>> reasonable to me.
>>>
>>> Are there use cases for filling with alternating values, as in `['x',
>>> 'y'].repeat(3)`?
>>>
>>>
>> _______________________________________________
>> es-discuss mailing list
>> [email protected]
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to