Proposal: Array.prototype.shuffle (Fisher-Yates)
axel at rauschma.de
Thu May 16 14:35:53 PDT 2013
If it was up to me, I’d add most if not all Underscore.js functions to the standard library (possibly via a module). The one function I most often miss is _.range() , which can be used for all kinds of things, including for filling an array with values:
> Array.range(5).map(() => 'x')
[ 'x', 'x', 'x', 'x', 'x' ]
A more principled approach to determine candidates for ES6 inclusion: search large code bases that depend on Underscore and determine how much each of its functions is actually used.
On May 16, 2013, at 23:02 , John Terenzio <john at terenz.io> wrote:
> Many scripting languages, such as Ruby, PHP, and Python (via the random module), have a built-in for properly shuffling an array. I propose adding Array.prototype.shuffle to the ES spec. I think it should act like Array.prototype.reverse, shuffling the array in place and returning a reference to it. It should use the Fisher-Yates algorithm. See https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
> Since this functionality is missing, some less-seasoned developers fall into the trap of using the "sort by random" method, which produces bias. See http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/
> In a perfect world, this would use a better random number generator than the existing Math.random, but for now an implementation like the one below would still be a vast improvement over having to implement manually and possibly incorrectly. See https://bugzilla.mozilla.org/show_bug.cgi?id=322529
> Example implementation: https://gist.github.com/jterenzio/28bb972f3abb7618b14b
> I don't think adding this to the spec would cause many compatibility issues and the implementation should be very straightforward. Let me know what you think!
> es-discuss mailing list
> es-discuss at mozilla.org
Dr. Axel Rauschmayer
axel at rauschma.de
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the es-discuss