Pure Random Number Generators

8.4.0 · active · verified Sun Apr 19

Pure-rand is a JavaScript and TypeScript library providing fast, pure pseudorandom number generators (PRNGs). Its core differentiator is the emphasis on purity: generator instances are immutable. This means each random number generation operation returns a new generator state alongside the generated value, enabling reproducible sequences and eliminating side effects, which is crucial for deterministic simulations, testing, and cryptographic applications where state integrity is paramount. The library offers various PRNG algorithms, such as Xoroshiro128+, and implements common statistical distributions like uniform integers. Currently at version 8.4.0, pure-rand maintains an active development and release cadence, providing reliable and performant random number generation. It aims to offer predictable and verifiable randomness, setting it apart from libraries that mutate generator state in place.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the library's core 'pure' usage model, where each random number generation returns a new generator state, ensuring immutability and reproducibility. It initializes a Xoroshiro128+ generator, purifies a uniform integer distribution, and shows how to generate a sequence of values while correctly managing the evolving immutable generator state.

import { uniformIntDistribution } from 'pure-rand/distribution/UniformIntDistribution';
import { xoroshiro128plus } from 'pure-rand/generator/xoroshiro128plus';
import { purify } from 'pure-rand/utils/purify';

const uniformIntDistributionPure = purify(uniformIntDistribution);

// A seed for reproducibility
const seed = 42;
// Initialize the PRNG. This creates an 'impure' generator.
const rng1 = xoroshiro128plus(seed);

// Use the purified distribution. It returns both the value and the *next* generator state.
const [firstDiceValue, rng2] = uniformIntDistributionPure(rng1, 1, 6);
console.log(`First roll: ${firstDiceValue}, Next RNG state hash: ${rng2.min()}`); // Example: 2

const [secondDiceValue, rng3] = uniformIntDistributionPure(rng2, 1, 6);
console.log(`Second roll: ${secondDiceValue}, Next RNG state hash: ${rng3.min()}`); // Example: 4

const [thirdDiceValue, rng4] = uniformIntDistributionPure(rng3, 1, 6);
console.log(`Third roll: ${thirdDiceValue}, Next RNG state hash: ${rng4.min()}`); // Example: 6

// Demonstrating purity: Calling with rng1 again produces the same result
const [replayedFirstValue, _] = uniformIntDistributionPure(rng1, 1, 6);
console.log(`Replayed first roll (from rng1): ${replayedFirstValue}`); // Example: 2

// Example of directly using an impure generator (less common in pure-rand's philosophy)
const impureRng = xoroshiro128plus(100);
const val1 = uniformInt(impureRng, 1, 10);
const val2 = uniformInt(impureRng, 1, 10);
console.log(`Impure sequence: ${val1}, ${val2}`);

view raw JSON →