Creating a filled array with a given length?

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Dec 12 08:59:09 PST 2012


Hilarious, I haven't seen anything similar to Array#unique yet which is
much more common operation ( see the needing of Set ) and you are
suggesting this that in my experience has basically no use cases except for
zero filled flat matrixes ? :-)

function repeat(times) {
  var out = [], i = parseInt(times, 10);
  while (i--)
    out[i] = this
  ;
  return out.concat.apply([], out);
}

repeat.call([1,2,3], 2); // => 1,2,3,1,2,3

for ES3 like environment ;)

br


On Tue, Dec 11, 2012 at 10:59 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

> I would still love to have something like that in ES6 (loosely similar to
> String.prototype.repeat). Once you have that, you can e.g. use
> Array.prototype.map to do more things.
>
> Two possibilities:
> - Array.repeat(undefined, 3) -> [ undefined, undefined, undefined ]
> - [ undefined ].repeat(3) -> [ undefined, undefined, undefined ]
>
> The same array could be created like this, but that seems too much work
> for a relatively common operation.
>
> 'x'.repeat(3).split('').map(=> undefined)
>
> --
> Dr. Axel Rauschmayer
> axel at rauschma.de
>
> home: rauschma.de
> twitter: twitter.com/rauschma
> blog: 2ality.com
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121212/def78e38/attachment-0001.html>


More information about the es-discuss mailing list