Skip to content

@technobuddha > library > Random > Shuffle

Function: randomShuffle()

ts
function randomShuffle<T>(deck: readonly T[], random: () => number): T[];

Defined in: random-shuffle.ts:19

Returns a new array with the elements of the input array shuffled in random order.

Uses the Fisher-Yates (Knuth) shuffle algorithm to ensure an unbiased shuffle.

Type Parameters

Type ParameterDescription
TThe type of elements in the array.

Parameters

ParameterTypeDefault valueDescription
deckreadonly T[]undefinedThe array of items to shuffle. The original array is not modified.
random() => numberMath.randomA function that returns a random number in the range [0, 1). Defaults to Math.random.

Returns

T[]

A new array containing the shuffled elements.

Example

typescript
const items = [1, 2, 3];
randomShuffle(items, () => 0.5); // deterministic shuffle for example
// result could be: [2, 3, 1]
randomShuffle([]); // []