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.
Maintainers
Readme
fast-array-shuffle
Ultra-fast, mathematically unbiased Fisher-Yates array shuffler, random sampling, weighted picking, and array partitioning in TypeScript with zero dependencies.
Why fast-array-shuffle?
A naive array shuffle like arr.sort(() => Math.random() - 0.5) is fundamentally broken:
- Biased Distribution: The probability of permutations is not uniform, favoring certain positions and creating measurable statistical skew.
- 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.
- Heavy Dependencies: Importing massive utility libraries like
lodashjust 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, andderange(e.g. Secret Santa permutations). - Seeded RNG Support: Pass custom PRNG functions (like
seedrandomor 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-shuffleQuick 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:
