From ee503b3bce55a5fb38e3edcbb9f5153f8f00916d Mon Sep 17 00:00:00 2001 From: Manav Rathi Date: Sat, 4 May 2024 18:37:39 +0530 Subject: [PATCH] Shuffle --- web/packages/utils/array.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 web/packages/utils/array.ts diff --git a/web/packages/utils/array.ts b/web/packages/utils/array.ts new file mode 100644 index 0000000000..d7c927d30b --- /dev/null +++ b/web/packages/utils/array.ts @@ -0,0 +1,15 @@ +/** + * 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. + */ +export const shuffle = (xs: T[]) => + xs + .map((x) => [Math.random(), x]) + .sort() + .map(([, x]) => x);