magnetar/fe_calckey/frontend/client/src/scripts/shuffle.ts

23 lines
575 B
TypeScript
Raw Normal View History

2023-07-07 19:22:30 +00:00
/**
* ()
*/
export function shuffle<T extends any[]>(array: T): T {
let currentIndex = array.length;
let randomIndex;
2023-07-07 19:22:30 +00:00
// While there remain elements to shuffle.
while (currentIndex !== 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
2023-07-07 19:22:30 +00:00
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
2023-07-07 19:22:30 +00:00
return array;
2023-07-07 19:22:30 +00:00
}