Skip to content

Instantly share code, notes, and snippets.

@MAKIO135
Last active June 18, 2018 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MAKIO135/3d2406a594700ec447ebd0b208ead916 to your computer and use it in GitHub Desktop.
Save MAKIO135/3d2406a594700ec447ebd0b208ead916 to your computer and use it in GitHub Desktop.
// Based on Fisher–Yates shuffle ( https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle )
// and Shuffling an Array in JavaScript ( https://www.kirupa.com/html5/shuffling_array_js.htm )
// returns a new array shuffled
Array.prototype.shuffle = function() {
let tmpArray = [ ... this ]; // create a copy of original array
for( let i = tmpArray.length - 1; i; i -- ) {
let randomIndex = ~~( Math.random() * ( i + 1 ) );
[ tmpArray[ i ], tmpArray[ randomIndex ] ] = [ tmpArray[ randomIndex ], tmpArray[ i ] ]; // swap
}
return tmpArray;
};
// permanently shuffles the array
Array.prototype.permShuffle = function() {
for( let i = this.length - 1; i; i -- ) {
let randomIndex = ~~( Math.random() * ( i + 1 ) );
[ this[ i ], this[ randomIndex ] ] = [ this[ randomIndex ], this[ i ] ]; // swap
}
return this;
};
/*
//Usage:
const arr = ( new Array( 5 ) ).fill( 0 ).map( ( d, i ) => i );
console.log( arr ); // [0, 1, 2, 3, 4]
console.log( arr.shuffle() ); // [0, 4, 1, 2, 3] <- returns a copy array shuffled
console.log( arr ); // [0, 1, 2, 3, 4] <- original array was not modified
console.log( arr.permShuffle() ); // [0, 1, 3, 4, 2] <- returns original array shuffled
console.log( arr ); // [0, 1, 3, 4, 2] <- original array was modified
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment