Skip to content

Instantly share code, notes, and snippets.

@ppraksa
Created September 2, 2024 11:30
Show Gist options
  • Select an option

  • Save ppraksa/e9fd30a38fabc18a01950973c8e9f36f to your computer and use it in GitHub Desktop.

Select an option

Save ppraksa/e9fd30a38fabc18a01950973c8e9f36f to your computer and use it in GitHub Desktop.
Array.prototype.shuffle = function () {
let c = [];
const MAX = this.length;
function testAndShuffle(item) {
let index = Math.floor(Math.random() * MAX);
if (typeof c[index] === "undefined") {
c[index] = item;
} else {
testAndShuffle(item);
}
}
this.forEach((item) => testAndShuffle(item));
return c;
};
console.log([1, 2, 3, 4, 5, 6].shuffle());
console.log([1, 2, 3, 4, 5, 6].shuffle());
console.log([1, 2, 3, 4, 5, 6].shuffle());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment