ente/web/packages/utils/array.ts

16 lines
522 B
TypeScript
Raw Normal View History

2024-05-04 13:07:39 +00:00
/**
* Shuffle.
*
* Return a new array containing the shuffled elements of the given array.
*
* The algorithm used is not the most efficient, but is effectively a one-liner
* whilst being reasonably efficient. To each element we assign a random key,
* then we sort by this key. Since the key is random, the sorted array will have
* the original elements in a random order.
*/
2024-05-04 13:18:43 +00:00
export const shuffled = <T>(xs: T[]) =>
2024-05-04 13:07:39 +00:00
xs
.map((x) => [Math.random(), x])
.sort()
2024-05-04 13:18:43 +00:00
.map(([, x]) => x) as T[];