shuffle

Mezcla aleatoriamente los elementos de un array usando el algoritmo Fisher-Yates.

#array #utility #random
export const shuffle = <T>(arr: readonly T[]): T[] => {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
// Usage
shuffle([1, 2, 3, 4, 5]);
// e.g., [3, 1, 5, 2, 4]

Comparte este snippet

Comentarios