That *could* repeat an array, but it's not very good as a polyfill (it
creates too many intermediate arrays). I'd expect a polyfill would be
closer to this:

```js
const ToInteger = x => (x = +x; x - x % 1)

Array.prototype.repeat = function repeat(count) {
    count = ToInteger(count)
    let o = Object(this)
    let length = ToInteger(o.length)
    let output = new Array(length * count)
    let i = 0
    while (i < count) {
        let j = 0
        while (j < length) output[i++] = o[j++]
    }
    return output
}
```

And while we're at it, could we also add a `Array.prototype.set` to
mirror `TypedArray.prototype.set`? I could've used that several times
already, and it's an easily vectorized operation.

-----

Isiah Meadows
[email protected]

Looking for web consulting? Or a new website?
Send me an email and we can get started.
www.isiahmeadows.com


On Sun, Mar 25, 2018 at 2:36 PM, Peter Jaszkowiak <[email protected]> wrote:
> I'm guessing this would be an appropriate polyfill:
>
> ```
> Array.prototype.repeat = function repeat(count) {
>   let output = this;
>   while (--count) {
>     output = output.concat(this);
>   }
>   return output;
> };
> ```
>
> On Sun, Mar 25, 2018 at 12:27 PM, Cyril Auburtin <[email protected]>
> wrote:
>>
>> String and Array share a few methods.
>>
>> I think `repeat` could exist for Array as well
>>
>> At the moment are other more verbose ways to do so:
>>
>> - `Array.from({length: n}, () => 'foo')`
>> - `Array(n).fill('foo')`
>> - `[].concat(...Array.from({length: 3}, () => ['x', 'y']))`
>> - `[].concat(...Array(3).fill(['x', 'y']))`
>>
>> so with repeat it would just be;
>>
>> - `['foo'].repeat(n)`
>> - `['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
>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to