Skip to content
VersionSize

shuffle

The shuffle utility creates a new array with the elements of the original array in a randomized order. It uses the efficient Fisher-Yates algorithm to ensure a truly uniform shuffle.

Implementation

View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';

/**
 * Shuffles an array randomly.
 *
 * @example
 * ```ts
 * const arr = [1, 2, 3, 4];
 * shuffle(arr); // a shuffled version of the array
 * ```
 *
 * @param array - The array to shuffle.
 *
 * @returns A new shuffled array.
 *
 * @throws {TypeError} If the provided array is not an array.
 */
export function shuffle<T>(array: T[]): T[] {
  assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });

  const result = [...array];

  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }

  return result;
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Uniform Distribution: Every possible permutation of the array has an equal probability.
  • Immutable: Returns a new array, leaving the original array unchanged.
  • Type-safe: Preserves the type of the array elements.

API

ts
function shuffle<T>(array: T[]): T[];

Parameters

  • array: The array to shuffle.

Returns

  • A new array containing the same elements in a random order.

Examples

Shuffling a Deck

ts
import { shuffle } from '@vielzeug/toolkit';

const deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffled = shuffle(deck);

console.log('Original:', deck);
console.log('Shuffled:', shuffled);

Randomizing a List of Users

ts
import { shuffle } from '@vielzeug/toolkit';

const players = ['Alice', 'Bob', 'Charlie', 'David'];
const randomOrder = shuffle(players);

Implementation Notes

  • Uses the Fisher-Yates (also known as Knuth) shuffle algorithm.
  • Complexity is $O(n)$ where $n$ is the length of the array.
  • Throws TypeError if the input is not an array.

See Also

  • draw: Pick a single random element from an array.
  • random: Generate a random number in a range.
  • sort: Sort an array based on a specific criteria.