shuffle
EditProduces a shuffled copy of an array using the Fisher–Yates algorithm.
/** Returns a shuffled copy using the Fisher–Yates algorithm. */export const shuffle = <const T>( array: readonly T[], random: (this: void) => number = Math.random,): T[] => { const shuffled: T[] = []; for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) { throw new TypeError("array must not contain empty slots"); } shuffled.push(array[index] as T); }
for (let index = shuffled.length - 1; index > 0; index -= 1) { const sample = random(); if (!Number.isFinite(sample) || sample < 0 || sample >= 1) { throw new RangeError( "random must return a number from 0 up to, but not including, 1", ); } const swapIndex = Math.floor(sample * (index + 1)); const current = shuffled[index] as T; shuffled[index] = shuffled[swapIndex] as T; shuffled[swapIndex] = current; }
return shuffled;};Download
Section titled “Download”wget -O src/lib/shuffle.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/shuffle.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/shuffle.ts" src/lib/shuffle.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { shuffle } from "./shuffle";
const cards = ["ace", "king", "queen", "jack"];const shuffledCards = shuffle(cards);
console.log(shuffledCards);console.log(cards); // The original order is unchanged.array(readonly T[]) — Dense values to shuffle. Sparse arrays are rejected.random(() => number, default:Math.random) — Receiver-free random source returning a number from0up to, but not including,1. Supply a seeded source for reproducible output.
Returns
Section titled “Returns”T[] — A shuffled copy. The input is not mutated.