shuffle
Returns a new array with the elements of the input in random order, using the Fisher-Yates algorithm. The input is not mutated. Pass an optional random function to inject a deterministic or seeded random source.
Try it
Section titled “Try it”Import
Section titled “Import”import { shuffle } from "1o1-utils";import { shuffle } from "1o1-utils/shuffle";Signature
Section titled “Signature”function shuffle<T>({ array, random }: ShuffleParams<T>): T[]Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| array | T[] | Yes | The array to shuffle |
| random | () => number | No | Random source returning a number in [0, 1). Defaults to Math.random. |
Returns
Section titled “Returns”T[] — A new array with the elements in random order.
Examples
Section titled “Examples”shuffle({ array: [1, 2, 3, 4, 5] });// => [3, 1, 5, 2, 4] (random)
const input = [1, 2, 3];shuffle({ array: input });// => some permutation; `input` is unchangedInject a deterministic random source for tests or seeded randomness:
shuffle({ array: [1, 2, 3, 4, 5], random: () => 0 });// => [2, 3, 4, 5, 1]Security
Section titled “Security”The default random is Math.random, which is not cryptographically secure. For adversarial contexts (raffles, sampling that must resist prediction), inject a CSPRNG-based source — for example one built on crypto.getRandomValues:
function cryptoRandom() { const buf = new Uint32Array(1); crypto.getRandomValues(buf); return buf[0] / 2 ** 32;}
shuffle({ array: items, random: cryptoRandom });Edge Cases
Section titled “Edge Cases”- Throws if
arrayis not an array. - Returns an empty array when given an empty array.
- Returns a single-element array unchanged.
- Always returns a new array reference; the input is never mutated.
- The
randomfunction must return a value in[0, 1). Out-of-range outputs are clamped to keep swap indices in bounds.
Also known as
Section titled “Also known as”randomize, scramble, fisher-yates, knuth-shuffle
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use shuffle to randomize an array, and how to inject a deterministic random source in tests