Skip to content

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.

import { shuffle } from "1o1-utils";
import { shuffle } from "1o1-utils/shuffle";
function shuffle<T>({ array, random }: ShuffleParams<T>): T[]
NameTypeRequiredDescription
arrayT[]YesThe array to shuffle
random() => numberNoRandom source returning a number in [0, 1). Defaults to Math.random.

T[] — A new array with the elements in random order.

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 unchanged

Inject a deterministic random source for tests or seeded randomness:

shuffle({ array: [1, 2, 3, 4, 5], random: () => 0 });
// => [2, 3, 4, 5, 1]

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 });
  • Throws if array is 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 random function must return a value in [0, 1). Out-of-range outputs are clamped to keep swap indices in bounds.

randomize, scramble, fisher-yates, knuth-shuffle

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