Skip to content

Commit 0648bcf

Browse files
committed
Make Array::shuffle safer
As mentioned by @dbrady in #72 we shouldn't overwrite a native `Array::shuffle`
1 parent 50ab300 commit 0648bcf

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Diff for: chapters/arrays/shuffling-array-elements.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ The following code adds the shuffle function to the Array prototype, which means
7979
you are able to run it on any array you wish, in a much more direct manner.
8080

8181
{% highlight coffeescript %}
82-
Array::shuffle = ->
82+
do -> Array::shuffle ?= ->
8383
for i in [@length-1..1]
8484
j = Math.floor Math.random() * (i + 1)
8585
[@[i], @[j]] = [@[j], @[i]]
@@ -92,7 +92,9 @@ Array::shuffle = ->
9292
**Note:** Although it's quite common in languages like Ruby, extending native objects is
9393
often considered bad practice in JavaScript (see: [Maintainable JavaScript: Don’t modify
9494
objects you don’t own][dontown]; [Extending built-in native objects. Evil or not?]
95-
[extendevil]).
95+
[extendevil]). That being said, the code above is really quite safe to add. It only adds
96+
`Array::shuffle` if it doesn't exist already, thanks to the existential assignment
97+
operator (`?=`). That way, we don't overwrite someone else's, or a native browser method.
9698

9799
Also, if you think you'll be using a lot of these utility functions, consider using a
98100
utility library, like [Lo-dash](http://lodash.com/). They include a lot of nifty

0 commit comments

Comments
 (0)