Skip to content

Instantly share code, notes, and snippets.

@hungdoansy
Created July 24, 2023 01:47
Show Gist options
  • Save hungdoansy/f789984f7807e1f90090559b03135085 to your computer and use it in GitHub Desktop.
Save hungdoansy/f789984f7807e1f90090559b03135085 to your computer and use it in GitHub Desktop.
Shuffle a list
// Source: https://stackoverflow.com/a/2450976/6812545
const shuffle = <T>(array: T[]): T[] => {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// Used like so
const arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment