Unbiased Fisher-Yates Shuffle

Shuffle arrays in place or on a copy using crypto-backed rejection sampling to avoid modulo bias and preserve uniform permutations.

JavascriptData Integrity

Code

javascriptsnippet
34 lines
export function shuffle(items, options = {}) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  const { copy = true } = options;
  const result = copy ? items.slice() : items;
  for (let index = result.length - 1; index > 0; index -= 1) {
    const swapIndex = randomInteger(index + 1);
    const temporary = result[index];
    result[index] = result[swapIndex];
    result[swapIndex] = temporary;
  }
  return result;
}

function randomInteger(exclusiveMax) {
  if (!Number.isInteger(exclusiveMax) || exclusiveMax < 1 || exclusiveMax > 0x100000000) {
    throw new RangeError("exclusiveMax must be an integer between 1 and 2^32");
  }
  if (typeof globalThis.crypto?.getRandomValues !== "function") {
    throw new Error("crypto.getRandomValues is required for an unbiased shuffle");
  }
  const limit = Math.floor(0x100000000 / exclusiveMax) * exclusiveMax;
  const buffer = new Uint32Array(1);
  let value = 0;
  do {
    globalThis.crypto.getRandomValues(buffer);
    value = buffer[0];
  } while (value >= limit);
  return value % exclusiveMax;
}

const deck = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(shuffle(deck));
console.log(shuffle(deck, { copy: false }));
console.log(deck.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[
  7, 3, 6, 1,
  5, 4, 2, 8
]
[
  6, 3, 8, 2,
  4, 7, 5, 1
]
8

How the snippet works

The working surface is the functions shuffle and randomInteger — everything else is wiring.

Repetition is confined to for (let index = result.length - 1; index > 0; index -= 1) — the rest of the file is straight-line. Invalid states are rejected up front: it throws TypeError, RangeError and Error instead of continuing with bad data.

What to watch for

  • Uses crypto, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard typeof globalThis.crypto?.getRandomValues !== "function" short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads export function shuffle(items, options = {})

The surface worth importing is shuffle; the helpers around it are private to the snippet.

Key statements

throw new Error("crypto.getRandomValues is required for an unbiased shuffle");
throw new RangeError("exclusiveMax must be an integer between 1 and 2^32");
if (!Array.isArray(items)) throw new TypeError("items must be an array");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
`TypeError`, `RangeError` and `Error` is raised at the guard (`typeof globalThis.crypto?.getRandomValues !== "function"`), so invalid state never reaches the main logic.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `shuffle`, `randomInteger` at load time.