npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

fast-array-shuffle

v1.0.0

Published

Ultra-fast, unbiased Fisher-Yates array shuffler, random sampling, weighted picking, and array partitioning in TypeScript with zero dependencies.

Readme

fast-array-shuffle

Ultra-fast, mathematically unbiased Fisher-Yates array shuffler, random sampling, weighted picking, and array partitioning in TypeScript with zero dependencies.

npm version npm downloads license bundle size sponsor


Why fast-array-shuffle?

A naive array shuffle like arr.sort(() => Math.random() - 0.5) is fundamentally broken:

  1. Biased Distribution: The probability of permutations is not uniform, favoring certain positions and creating measurable statistical skew.
  2. Poor Performance: Array sorting is $O(n \log n)$ comparisons with redundant swaps, whereas the modern Fisher-Yates (Knuth) algorithm runs in linear $O(n)$ time.
  3. Heavy Dependencies: Importing massive utility libraries like lodash just to shuffle or sample an array adds unnecessary bloat.

fast-array-shuffle solves all these problems:

  • 100% Unbiased: Implements the modern Fisher-Yates algorithm for uniform random permutations.
  • Pure & Immutable by Default: Returns a new array copy without mutating the original input, or pass { inPlace: true } for maximum memory performance.
  • Zero Dependencies: Pure TypeScript, tiny footprint (<700 bytes minified & gzipped).
  • Batteries Included: Includes shuffle, sample, sampleOne, partition, weightedSample, and derange (e.g. Secret Santa permutations).
  • Seeded RNG Support: Pass custom PRNG functions (like seedrandom or crypto generators) for reproducible tests and game seeds.

Installation

Install using your preferred package manager:

# npm
npm install fast-array-shuffle

# pnpm
pnpm add fast-array-shuffle

# yarn
yarn add fast-array-shuffle

# bun
bun add fast-array-shuffle

Quick Start

import { shuffle, sample, sampleOne, partition, weightedSample } from 'fast-array-shuffle';

// 1. Unbiased Fisher-Yates shuffle (immutable by default)
const deck = ['♠A', '♥K', '♦Q', '♣J', '10', '9'];
const shuffledDeck = shuffle(deck);
console.log(shuffledDeck);
// original array is untouched!

// 2. Sample random items without replacement
const lotteryNumbers = Array.from({ length: 49 }, (_, i) => i + 1);
const winningNumbers = sample(lotteryNumbers, 6);
console.log(winningNumbers); // e.g. [7, 23, 14, 42, 9, 31]

// 3. Pick a single random item
const prizes = ['Laptop', 'Coffee Mug', 'Sticker', 'Keyring'];
const won = sampleOne(prizes);

// 4. Partition items by predicate
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const [even, odd] = partition(numbers, (n) => n % 2 === 0);
console.log(even); // [2, 4, 6, 8, 10]
console.log(odd);  // [1, 3, 5, 7, 9]

Real-World Examples

Example 1: In-Place High Performance Shuffling

When dealing with massive arrays (e.g., 100,000+ items in a game engine or simulation), you can avoid memory allocations by enabling inPlace: true:

import { shuffle } from 'fast-array-shuffle';

const largeDataset = new Float64Array(50000);
// fill array...

// Mutates in-place for maximum performance with 0 extra allocations
shuffle(largeDataset, { inPlace: true });

Example 2: Reproducible Seeded Shuffling for Games & Testing

Pass a custom pseudorandom number generator (PRNG) to achieve deterministic, reproducible shuffles:

import { shuffle } from 'fast-array-shuffle';

// Simple deterministic linear congruential generator (LCG)
function createSeededRng(seed: number) {
  let s = seed;
  return () => {
    s = (s * 1664525 + 1013904223) % 4294967296;
    return s / 4294967296;
  };
}

const mapTiles = ['forest', 'desert', 'water', 'mountain', 'swamp'];
const seed = 987654321;

const mapGen1 = shuffle(mapTiles, { rng: createSeededRng(seed) });
const mapGen2 = shuffle(mapTiles, { rng: createSeededRng(seed) });

console.log(JSON.stringify(mapGen1) === JSON.stringify(mapGen2)); // true!

Example 3: Weighted Loot Drops in Games

Assign drop chances to items and select using weightedSample:

import { weightedSample } from 'fast-array-shuffle';

const lootTable = ['Common Sword', 'Rare Shield', 'Legendary Bow', 'Mythic Helmet'];
const weights = [70, 20, 9, 1]; // 70%, 20%, 9%, 1%

const itemDropped = weightedSample(lootTable, weights);
console.log(`You obtained: ${itemDropped}`);

Example 4: Secret Santa / Fair Exchange (Derangements)

In a Secret Santa draw, nobody should be assigned to give a gift to themselves. The derange function computes a permutation where zero items stay at their original index:

import { derange } from 'fast-array-shuffle';

const participants = ['Alice', 'Bob', 'Charlie', 'Diana', 'Evan'];
const assignedRecipients = derange(participants);

participants.forEach((giver, index) => {
  console.log(`${giver} -> gives gift to -> ${assignedRecipients[index]}`);
  // Guaranteed: giver !== assignedRecipients[index]
});

API Reference

shuffle<T>(array, options?)

Shuffles an array using the unbiased Fisher-Yates algorithm.

| Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | array | readonly T[] \| T[] | required | Source array to shuffle | | options.inPlace | boolean | false | If true, mutates the source array directly | | options.rng | () => number | Math.random | Custom random generator (0 to 1) |

Returns: T[] - Shuffled array.


sample<T>(array, count?, options?)

Extracts count unique random elements from an array without replacement using an optimal $O(\text{count})$ partial Fisher-Yates selection.

| Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | array | readonly T[] | required | Source array | | count | number | 1 | Number of items to sample | | options.rng | () => number | Math.random | Custom random generator |

Returns: T[] - Array of sampled elements.


sampleOne<T>(array, options?)

Selects a single random element from the array.

Returns: T | undefined - The picked element, or undefined if the array is empty.


partition<T>(array, predicate)

Splits an array into a tuple [passed, failed] according to a predicate function.

| Parameter | Type | Description | | :--- | :--- | :--- | | array | readonly T[] | Array to partition | | predicate | (item: T, index: number, array: readonly T[]) => boolean | Condition test |

Returns: [T[], T[]] - [truthyItems, falsyItems].


weightedSample<T>(items, weights, options?)

Picks an item from items according to numeric probabilities specified in weights.


derange<T>(array, options?)

Generates a derangement: a permutation of array where no item remains at its original index ($P(i) \neq i$ for all $i$).


TypeScript Interfaces

export interface ShuffleOptions {
  inPlace?: boolean;
  rng?: () => number;
}

export interface SampleOptions {
  rng?: () => number;
}

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.


License

MIT © Pirapaakaran Pirathapan

Support & Sponsor

If you find this utility useful in your applications, please consider supporting my open-source work:

💖 Sponsor Piratha97 on GitHub