Last active
January 16, 2018 17:39
-
-
Save joshuacerbito/b441935dd733095b646d040e879ad521 to your computer and use it in GitHub Desktop.
An extension to the Array class that returns a shuffled version of an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Array.shuffle | |
* | |
* Usage: | |
* const arr1 = [1, 2, 3, 4, 5]; | |
* const arr2 = Array.shuffle(arr1); | |
* const arr3 = arr1.shuffle(); | |
* | |
* @TODO: | |
* - Add callback functionality to Array.prototype.shuffle | |
*/ | |
if (!Array.shuffle) { | |
Array.shuffle = function(items) { | |
var currentIndex = items.length, temporaryValue, randomIndex; | |
while (0 !== currentIndex) { | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
temporaryValue = items[currentIndex]; | |
items[currentIndex] = items[randomIndex]; | |
items[randomIndex] = temporaryValue; | |
} | |
return items; | |
} | |
} | |
if(!Array.prototype.shuffle) { | |
Array.prototype.shuffle = function() { | |
return Array.shuffle(this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment