Pandemonium

2.4.1 · active · verified Sun Apr 19

Pandemonium is a lightweight JavaScript and TypeScript library providing a collection of common random-related utility functions. Currently stable at version 2.4.1, it offers functionalities such as `choice` for selecting random items, `random` for generating numbers within a range, `shuffle` for array randomization, and various specialized sampling algorithms like `reservoirSample` and `geometricReservoirSample`. A key differentiator is its modular design, allowing users to create custom versions of any function by injecting a specific random number generator (RNG) source, enabling seeded or otherwise controlled randomness. The library emphasizes performance for its sampling methods, offering detailed complexity analysis. Its release cadence is not explicitly stated in the provided documentation, but the package appears actively maintained with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic random number and selection utilities like `choice`, `random`, and `shuffle` from Pandemonium. It also illustrates a key feature: how to integrate a custom random number generator (e.g., `seedrandom`) to create reproducible random sequences, which is essential for testing or specific application needs.

import { choice, random, shuffle } from 'pandemonium';
import { createRandom } from 'pandemonium/random';
import seedrandom from 'seedrandom'; // Ensure 'seedrandom' is installed: npm install seedrandom

// Basic usage of random utilities
const fruits = ['apple', 'banana', 'cherry', 'date'];
console.log('Random fruit:', choice(fruits));

const randomNumber = random(10, 20); // Integer between 10 and 20 (inclusive)
console.log('Random number (10-20):', randomNumber);

const numbersToShuffle = [1, 2, 3, 4, 5];
const shuffledNumbers = shuffle(numbersToShuffle); // Returns a new shuffled array
console.log('Shuffled numbers:', shuffledNumbers);

// Demonstrating custom RNG for reproducible results
const seed = 'my_secret_seed';
const seededRNG = seedrandom(seed); // Create a seeded RNG function

// Create a custom random function using the injected seeded RNG
const reproducibleRandom = createRandom(seededRNG);

console.log(`\nReproducible random numbers with seed "${seed}":`);
for (let i = 0; i < 3; i++) {
  console.log(`  Run ${i + 1}:`, reproducibleRandom(1, 100));
}

// Verify reproducibility by creating another instance with the same seed
const anotherSeededRNG = seedrandom(seed);
const anotherReproducibleRandom = createRandom(anotherSeededRNG);
console.log(`Reproducible random numbers (second run with same seed "${seed}"):`);
for (let i = 0; i < 3; i++) {
  console.log(`  Run ${i + 1}:`, anotherReproducibleRandom(1, 100));
}

view raw JSON →