Skip to content

Instantly share code, notes, and snippets.

@jossmac
Created August 14, 2018 06:19
Show Gist options
  • Save jossmac/d3d5a92f885f5608cbab2e2a50d7957e to your computer and use it in GitHub Desktop.
Save jossmac/d3d5a92f885f5608cbab2e2a50d7957e to your computer and use it in GitHub Desktop.
A function to shuffle an array of items
/**
* This function shuffles an array of items.
* @param arr {Array} array of items
* @param clone {Boolean} immutable or not
* @returns {Array} the array of items in random order.
*/
function shuffle(arr, clone) {
var array = clone ? arr.slice(0) : arr;
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
const cards = new Array(52).fill(1).map((x, i) => i);
console.log(cards); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
console.log(shuffle(cards)); // [37, 29, 51, 5, 33, 30, 48, 31, 38, 21, 49, 26, 35, 7, 8, 32, 11, 42, 25, 1, 23, 17, 27, 6, 14, 4, 40, 34, 50, 12, 3, 18, 0, 28, 15, 39, 41, 46, 20, 36, 9, 22, 43, 2, 45, 13, 19, 24, 10, 16, 47, 44]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment