Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active January 16, 2018 17:39
Show Gist options
  • Save joshuacerbito/b441935dd733095b646d040e879ad521 to your computer and use it in GitHub Desktop.
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
/*
* 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