Skip to content

Instantly share code, notes, and snippets.

@imehr
Created March 23, 2013 07:29
Show Gist options
  • Save imehr/5226810 to your computer and use it in GitHub Desktop.
Save imehr/5226810 to your computer and use it in GitHub Desktop.
#javascript - Fisher-Yates shuffle
jQuery.fn.shuffleChildren = (function(){
function fisherYatesShuffle(arr) {
// Fisher-Yates shuffle has been proven
// to be more random than the conventional
// arr.sort(function(){return Math.random()-.5})
// http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html
var i = arr.length,
r, tempI, tempR;
if ( i === 0 ) {
return arr;
}
while ( i-- ) {
// Generate random index:
r = Math.floor(Math.random() * (i + 1));
// Shuffle:
tempI = arr[i];
tempR = arr[r];
arr[i] = tempR;
arr[r] = tempI;
}
return arr;
}
return function(doQuick) {
return this.each(function(){
var container = jQuery(this),
parentNode = this.parentNode,
nextSibling = this.nextSibling;
if (doQuick) {
// Remove from document
container.detach();
}
// Append shuffled children
container.append(
fisherYatesShuffle(container.children())
);
if (doQuick) {
// Insert at the correct location in the document
parentNode.insertBefore(container[0], nextSibling);
}
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment