Skip to content

RansuApi

Defined in: src/namespace/index.ts:86

The shape of the default export, derived from the object itself.

  • Omit<typeof api, "default">

RansuApi(): number

Defined in: src/namespace/index.ts:88

Shorthand for RansuApi.random.

number

AliasTable: typeof AliasTable

Defined in: src/namespace/index.ts:57

Omit.AliasTable


alphabets: object

Defined in: src/namespace/index.ts:45

The named alphabets string() accepts, for building your own.

readonly alphanumeric: string

readonly ascii: “!"#$%&‘()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}” = “!"#$%&’()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}

readonly base32: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"

readonly base32hex: "0123456789ABCDEFGHIJKLMNOPQRSTUV" = "0123456789ABCDEFGHIJKLMNOPQRSTUV"

readonly base58: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

readonly base62: string

readonly base64url: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

readonly binary: "01" = "01"

readonly digits: "0123456789" = DIGITS

readonly hex: "0123456789abcdef" = "0123456789abcdef"

readonly hexUpper: "0123456789ABCDEF" = "0123456789ABCDEF"

readonly letters: string

readonly lower: "abcdefghijklmnopqrstuvwxyz" = LOWER

readonly octal: "01234567" = "01234567"

readonly unambiguous: "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

readonly upper: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" = UPPER

import { alphabets, string } from "ransu";
string(8, alphabets.lower); // "qmzdfhbx"
string(8, alphabets.alphanumeric); // the default
string(8, alphabets.hex + alphabets.upper); // combine them as strings

Omit.alphabets


angle: () => number

Defined in: src/geometry.ts:142

A uniform angle in radians, in [0, 2pi).

number

angle(); // 2.4913...

Omit.angle


angleDegrees: () => number

Defined in: src/geometry.ts:154

A uniform angle in degrees, in [0, 360).

number

angleDegrees(); // 142.74...

Omit.angleDegrees


backoff: (attempt, options) => number

Defined in: src/time.ts:128

How long to wait before retry number attempt, counting from 0.

Retrying on a fixed schedule makes every client in a fleet retry at the same instant; the jitter strategies exist to break that up.

number

BackoffOptions = {}

number

backoff(0); // 87.3 around 100ms
backoff(1); // 213.9 around 200ms
backoff(4); // 1483.2 around 1.6s, capped by maxDelay
backoff(3, { base: 250, factor: 3, jitter: "equal" });

Omit.backoff


bates: (n) => number

Defined in: src/global/distributions.ts:235

One draw: the mean of n uniforms.

number

number

bates(10); // 0.5127...

Omit.bates


below: (n) => number

Defined in: src/global/numbers.ts:52

An integer in [0, n). The form array indices want.

number

number

const items = ["a", "b", "c"];
items[below(items.length)]; // "c"

Omit.below


bernoulli: (p) => number

Defined in: src/global/distributions.ts:276

1 with probability p, otherwise 0.

number = 0.5

number

bernoulli(); // 1
bernoulli(0.25); // 0

Omit.bernoulli


beta: (alpha, betaShape) => number

Defined in: src/global/distributions.ts:77

One draw in (0, 1), shaped by two positive parameters.

number

number

number

beta(2, 5); // 0.2734... skewed toward 0

Omit.beta


bigBits: (n) => bigint

Defined in: src/global/numbers.ts:151

An integer built from n random bits, with no width limit.

number

bigint

bigBits(256); // 8873184...n

Omit.bigBits


bigint: (min, max) => bigint

Defined in: src/global/numbers.ts:78

A bigint in [min, max], both ends included.

bigint

bigint

bigint

bigint(0n, 2n ** 128n); // 214703556478...n

Omit.bigint


binomial: (n, p) => number

Defined in: src/global/distributions.ts:301

The number of successes in n independent trials.

number

number

number

binomial(10, 0.5); // 6

Omit.binomial


bits: (n) => number

Defined in: src/global/numbers.ts:139

An integer built from n random bits, up to 53.

number

number

bits(8); // 173 an integer in [0, 256)
bits(53); // 6519085048561357

Omit.bits


bool: () => boolean

Defined in: src/global/numbers.ts:90

true or false, evenly.

boolean

bool(); // true

Omit.bool


bucket: (key, buckets, salt?) => number

Defined in: src/hash.ts:80

A stable bucket in [0, buckets) for key. Evenly spread across keys.

Seed

number

Seed

number

bucket("user-42", 16); // 11, the shard this user always lands in

Omit.bucket


bytes: (n) => Uint8Array

Defined in: src/global/numbers.ts:163

n random bytes.

number

Uint8Array

bytes(16); // Uint8Array(16) [ 57, 129, 123, ... ]

Omit.bytes


categorical: (weights) => number

Defined in: src/global/distributions.ts:289

An index in [0, weights.length), proportional to the weights.

ArrayLike<number>

number

categorical([1, 3, 6]); // 2, most of the time

Omit.categorical


cauchy: (location, scale) => number

Defined in: src/global/distributions.ts:125

One Cauchy draw. It has no mean, so expect extreme outliers.

number = 0

number = 1

number

cauchy(); // -0.4142... and occasionally something enormous

Omit.cauchy


chance: (p) => boolean

Defined in: src/global/numbers.ts:102

true with probability p.

number

boolean

chance(0.25); // true a quarter of the time

Omit.chance


char: (options?) => string

Defined in: src/global/strings.ts:58

A uniformly chosen character, as a string of one code point.

UnicodeOptions | CodePointSet

string

char(); // "符"
char({ blocks: "emoji" }); // an emoji
char({ blocks: ["hiragana", "katakana"] }); // "ネ"

Omit.char


chars: (length, options?) => string

Defined in: src/global/strings.ts:74

A random string of length code points, not UTF-16 units.

An astral character costs two UTF-16 units, so chars(10) can return a string whose .length is more than ten. The count is of characters.

number

UnicodeOptions | CodePointSet

string

chars(8, { blocks: "kana" }); // "へソむリあヴんケ"
chars(5, { blocks: "emoji" }).length; // 10, five astral characters

Omit.chars


chiSquared: (df) => number

Defined in: src/global/distributions.ts:89

One chi-squared draw with df degrees of freedom.

number

number

chiSquared(3); // 2.3661...

Omit.chiSquared


choices: <T>(items, k) => T[]

Defined in: src/global/collections.ts:80

k elements with replacement, so k may exceed the collection size.

T

Collection<T>

number

T[]

choices(["a", "b"], 5); // [ "b", "b", "a", "b", "a" ]

Omit.choices


codePoint: (options?) => number

Defined in: src/global/strings.ts:44

A uniformly chosen Unicode code point. Defaults to the printable blocks.

UnicodeOptions | CodePointSet

number

codePoint(); // 12441
codePoint({ blocks: "hiragana" }); // 12395

Omit.codePoint


CodePointSet: typeof CodePointSet

Defined in: src/namespace/index.ts:58

Omit.CodePointSet


coin: () => "heads" | "tails"

Defined in: src/dice.ts:206

Heads or tails, for when a boolean would read worse at the call site.

"heads" | "tails"

coin(); // "heads"

Omit.coin


color: (options) => string

Defined in: src/color.ts:147

A CSS colour string.

Hex by default. Opacity only appears when alpha was asked for, so the common case stays #rrggbb.

ColorOptions = {}

string

color(); // "#3e81d6"
color({ format: "rgb" }); // "rgb(62 129 214)"
color({ format: "hsl" }); // "hsl(214 62% 55%)"
color({ alpha: true }); // "#3e81d64f" a random alpha
color({ alpha: 0.5 }); // "#3e81d680" a fixed one
color({ format: "rgb", alpha: 0.4 }); // "rgb(62 129 214 / 0.4)"
// Constrain any channel to a value or an inclusive range.
color({ hue: [200, 240], saturation: 0.7, lightness: [0.3, 0.5] });

Omit.color


combination: <T>(items, k) => T[]

Defined in: src/global/collections.ts:104

k distinct elements, kept in their original order.

T

Collection<T>

number

T[]

combination([1, 2, 3, 4, 5], 3); // [ 1, 4, 5 ]

Omit.combination


d10: (count?) => number

Defined in: src/dice.ts:165

A 10-sided die, or count of them summed.

number

number

d10(); // 7
d10(2); // the sum of two

Omit.d10


d100: (count?) => number

Defined in: src/dice.ts:196

A percentile die: 1 to 100.

number

number

d100(); // 73

Omit.d100


d12: (count?) => number

Defined in: src/dice.ts:175

A 12-sided die, or count of them summed.

number

number

d12(); // 9
d12(2); // the sum of two

Omit.d12


d20: (count?) => number

Defined in: src/dice.ts:187

A 20-sided die, or count of them summed.

The one a critical hit is measured against.

number

number

d20(); // 17
d20(2); // the sum of two

Omit.d20


d4: (count?) => number

Defined in: src/dice.ts:132

A four-sided die, or count of them summed.

number

number

d4(); // 3
d6(3); // 11, the sum of three d6
d20(); // 17

Omit.d4


d6: (count?) => number

Defined in: src/dice.ts:145

A six-sided die, or count of them summed.

d4 through d100 are the same shape; reach for dice when the notation comes from data rather than from your own code.

number

number

d6(); // 4
d6(3); // 11, the sum of three

Omit.d6


d8: (count?) => number

Defined in: src/dice.ts:155

A 8-sided die, or count of them summed.

number

number

d8(); // 5
d8(2); // the sum of two

Omit.d8


date: (from, to) => Date

Defined in: src/time.ts:24

A Date in [from, to).

TimeInput

TimeInput

Date

date(new Date("2020-01-01"), new Date("2030-01-01")); // 2026-08-23T09:12:44.019Z
date(0, Date.now()); // any moment since the epoch; numbers are epoch millis

Omit.date


default: RansuApi

Defined in: src/namespace/index.ts:90

Present so require('ransu').default also works.


dice: DiceApi

Defined in: src/dice.ts:98

Roll dice written the way people already write them.

dice() gives the total; dice.detail() also reports what each die showed, for a log or an on-screen roll.

dice("3d6"); // 11
dice("d20"); // 17
dice("2d10+3"); // 14
dice("1d4-1"); // 2
dice.detail("4d6+2"); // { total: 17, dice: [ 3, 6, 2, 4 ], modifier: 2 }

Omit.dice


dirichlet: (alpha) => number[]

Defined in: src/global/distributions.ts:262

One point on the simplex: values in (0, 1) that sum to 1.

readonly number[]

number[]

dirichlet([1, 1, 1]); // [ 0.24, 0.51, 0.25 ]

Omit.dirichlet


distributions: distribution

Defined in: src/namespace/index.ts:50

Omit.distributions


duration: (min, max) => number

Defined in: src/time.ts:66

A duration in milliseconds, in [min, max).

number

number

number

duration(500, 2_000); // 1342

Omit.duration


engine: () => Engine

Defined in: src/global/index.ts:5

The engine every top-level function currently draws from.

Engine

engine().algorithm; // "Math.random" until you call seed()

Omit.engine


engines: object

Defined in: src/namespace/index.ts:51

Every engine ransu ships, as seedable factories.

chacha20: (seed?) => ChaCha20

ChaCha20 — a cryptographic stream cipher used as a generator.

The only engine that is both seedable and unpredictable: knowing any number of outputs does not reveal the rest. Use it when a stream must be reproducible and resistant to prediction; for secrets with no reproducibility requirement, ransu/secure is simpler.

Seed

ChaCha20

const source = chacha20(12345);
source.nextUint32(); // 1274611588
// Reproducible, unlike the platform CSPRNG.
chacha20(1).nextUint32() === chacha20(1).nextUint32(); // true

cryptoRandom: CryptoEngine

The platform CSPRNG, wrapped as an engine.

crypto.getRandomValues in browsers, workers and edge runtimes; node:crypto on Node. Unpredictable, and for that reason not seedable — which is what backs ransu/secure and the identifier functions.

cryptoRandom.nextUint32(); // unpredictable
cryptoRandom.seedable; // false
new Random(cryptoRandom).pick(["a", "b", "c"]);

mt19937: typeof mt19937

mulberry32: (seed?) => Mulberry32

mulberry32 — 32 bits of state, a dozen lines of arithmetic.

The smallest engine here. Its 2^32 period is short enough to matter in a long run, so prefer it only where the state size is the constraint.

Seed

Mulberry32

const source = mulberry32(42);
source.nextUint32(); // 2744357186

nativeMath: NativeMathEngine

Math.random, wrapped as an engine.

Not seedable and not reproducible: the host owns the state. This is what the global functions draw from until you call seed().

nativeMath.nextUint32(); // 2166136261
nativeMath.seedable; // false

pcg32: (seed?) => Pcg32

PCG32 — a 64-bit LCG whose output is permuted before it is returned.

Statistically excellent for its size, and it supports multiple independent streams from one seed.

Seed

Pcg32

const source = pcg32(42);
source.nextUint32(); // 2722782280

sfc32: (seed?) => Sfc32

sfc32 — Small Fast Counting, 128 bits of state.

About as fast as anything here and very small. Chosen when speed matters more than a proven period.

Seed

Sfc32

const source = sfc32(42);
source.nextUint32(); // 261194151

xoshiro128pp: (seed?) => Xoshiro128pp

xoshiro128++ — 128 bits of state, the default engine.

Fast, small, and passes BigCrush. Its period of 2^128-1 is far more than any single program will draw, but it is not cryptographic: a few outputs are enough to recover the state and predict the rest.

Seed

Xoshiro128pp

const source = xoshiro128pp(42);
source.nextUint32(); // 167929222
new Random(source).integer(1, 6); // 3

xoshiro256pp: (seed?) => Xoshiro256pp

xoshiro256++ — 256 bits of state.

The same family as xoshiro128pp with a longer period, and the one to pick when you need jump() to hand disjoint streams to parallel workers.

Seed

Xoshiro256pp

const source = xoshiro256pp(42);
source.nextUint32(); // 1573169414
// Non-overlapping streams for parallel work.
const [a, b, c] = source.split(3);
// Pick one for a Random, or for the global stream.
new Random(42, { engine: engines.pcg32 });
// Or build one directly and hand it around.
const source = engines.xoshiro256pp(42);
source.nextUint32(); // 1573169414
engines.mt19937(42); // for reproducing another language's stream
engines.chacha20(42); // cryptographic, and still reproducible
engines.cryptoRandom; // the platform CSPRNG, not seedable
engines.nativeMath; // Math.random, not seedable

Omit.engines


exponential: (rate) => number

Defined in: src/global/distributions.ts:38

One exponential draw: the wait until the next event.

number = 1

number

exponential(); // 0.6931... rate 1
exponential(0.5); // 3.2188... the mean is 1 / rate

Omit.exponential


fillBytes: (out) => void

Defined in: src/global/numbers.ts:176

Fill an existing buffer, with no allocation.

Uint8Array

void

const buffer = new Uint8Array(32);
fillBytes(buffer);

Omit.fillBytes


fisherF: (d1, d2) => number

Defined in: src/global/distributions.ts:113

One F draw, the ratio of two chi-squared variables.

number

number

number

fisherF(3, 10); // 1.1274...

Omit.fisherF


float: (min?, max?) => number

Defined in: src/global/numbers.ts:26

A double in [min, max), or [0, 1) with no arguments.

number

number

number

float(); // 0.3964157...
float(10); // 6.2831853... one argument is the upper bound
float(-1.5, 1.5); // 0.4142135...

Omit.float


floats: (n) => Float64Array

Defined in: src/global/numbers.ts:188

n doubles in [0, 1).

number

Float64Array

floats(1_000); // Float64Array(1000) [ 0.396..., 0.364..., ... ]

Omit.floats


futureDate: (days) => Date

Defined in: src/time.ts:53

A Date within the next days (default 7).

number = 7

Date

futureDate(30); // some time in the next month

Omit.futureDate


gamma: (shape, scale) => number

Defined in: src/global/distributions.ts:52

One gamma draw.

number

number = 1

number

gamma(2); // 1.4726...
gamma(2, 10); // 14.726... shape 2, scale 10

Omit.gamma


geometric: (p) => number

Defined in: src/global/distributions.ts:326

The trial on which the first success lands, counting from 1.

number

number

geometric(0.1); // 7

Omit.geometric


getState: () => EngineState

Defined in: src/global/index.ts:5

A JSON-serialisable snapshot of the global stream.

EngineState

seed(1);
const saved = getState();
const first = random();
setState(saved);
random() === first; // true

Omit.getState


graphemes: (value, locale?) => string[]

Defined in: src/namespace/index.ts:46

A random string of count grapheme clusters — what a reader calls “characters”.

A flag or an emoji with a skin-tone modifier is several code points that display as one glyph. chars counts code points and would split them; this counts what you see.

string

string

string[]

graphemes(3); // three visible characters, whatever they cost in code points

Omit.graphemes


gumbel: (location, scale) => number

Defined in: src/global/distributions.ts:161

One Gumbel draw: the distribution of a maximum.

number = 0

number = 1

number

gumbel(); // 0.4759...

Omit.gumbel


hashFloat: (key, salt?) => number

Defined in: src/hash.ts:39

A stable double in [0, 1) for key.

Seed

Seed

number

hashFloat("user-42"); // 0.6031... always this value
hashFloat("user-42", "experiment-b"); // 0.1187... a different salt, a different answer

Omit.hashFloat


hashInteger: (key, min, max, salt?) => number

Defined in: src/hash.ts:51

A stable integer in [min, max] for key.

Seed

number

number

Seed

number

hashInteger("user-42", 1, 6); // 3, on every machine and every run

Omit.hashInteger


hashPick: <T>(key, items, salt?) => T

Defined in: src/hash.ts:68

A stable choice from items for key.

T

Seed

Collection<T>

Seed

T

hashPick("user-42", ["control", "blue", "green"]); // "blue"

Omit.hashPick


hashRandom: (key, salt?) => Random

Defined in: src/hash.ts:111

A whole Random seeded from key, when one value is not enough.

Seed

Seed

Random

const rng = hashRandom("user-42");
rng.integer(1, 6); // 5
rng.pick(["red", "blue"]); // "blue"
// Same key, same sequence, in any process.

Omit.hashRandom


hex: (length) => string

Defined in: src/global/strings.ts:31

A random lowercase hexadecimal string.

number

string

hex(32); // "3f7a1c05e2b8..."

Omit.hex


hsl: (options) => [number, number, number, number]

Defined in: src/color.ts:68

[hue, saturation, lightness, alpha], with hue in degrees.

Alpha is 1 unless you ask for it, so the tuple is always four long.

ColorOptions = {}

[number, number, number, number]

hsl(); // [ 214, 0.62, 0.55, 1 ]
hsl({ hue: [200, 240] }); // blues only
hsl({ saturation: 0.8, lightness: [0.4, 0.6] });

Omit.hsl


hypergeometric: (population, successes, draws) => number

Defined in: src/global/distributions.ts:350

Successes when drawing without replacement from a finite pool.

number

number

number

number

hypergeometric(50, 5, 10); // 1, drawing 10 from 50 that hold 5

Omit.hypergeometric


inCircle: (radius) => Point

Defined in: src/geometry.ts:77

A uniform point inside a disc.

The square root matters: without it, points bunch up at the centre, because the area at radius r grows with r.

number = 1

Point

inCircle(50); // [ 12.4, -31.8 ] evenly spread over the disc

Omit.inCircle


inRect: (rect) => Point

Defined in: src/geometry.ts:124

A uniform point inside a rectangle.

Rect

Point

inRect({ x: 0, y: 0, width: 1920, height: 1080 }); // [ 842.1, 219.7 ]

Omit.inRect


inSphere: (radius, dimensions) => Point

Defined in: src/geometry.ts:108

A uniform point inside a ball, by volume.

number = 1

number = 3

Point

inSphere(10); // [ 3.1, -5.7, 1.2 ]

Omit.inSphere


integer: (min, max) => number

Defined in: src/global/numbers.ts:39

An integer in [min, max], both ends included.

number

number

number

integer(1, 6); // 4
integer(-10, 10); // -3

Omit.integer


integers: (n, min, max) => Float64Array

Defined in: src/global/numbers.ts:200

n integers in [min, max], with the bounds validated once.

number

number

number

Float64Array

integers(1_000, 1, 6); // Float64Array(1000) [ 3, 5, 3, 1, ... ]

Omit.integers


irwinHall: (n) => number

Defined in: src/global/distributions.ts:223

One draw: the sum of n uniforms.

number

number

irwinHall(12); // 6.1284... a cheap normal approximation

Omit.irwinHall


jitter: (base, factor) => number

Defined in: src/time.ts:83

Spread a value by +/- factor so that things scheduled together stop arriving together. jitter(1000, 0.1) lands in [900, 1100).

number

number = 0.1

number

jitter(1_000); // 964.27... within 10%
jitter(1_000, 0.5); // 1387.51... within 50%

Omit.jitter


laplace: (location, scale) => number

Defined in: src/global/distributions.ts:137

One Laplace draw: two exponential tails back to back.

number = 0

number = 1

number

laplace(0, 1); // 0.3819...

Omit.laplace


logistic: (location, scale) => number

Defined in: src/global/distributions.ts:149

One logistic draw, the distribution behind the sigmoid.

number = 0

number = 1

number

logistic(); // -0.2231...

Omit.logistic


logNormal: (mu, sigma) => number

Defined in: src/global/distributions.ts:65

One log-normal draw: a normal variable exponentiated.

number = 0

number = 1

number

logNormal(); // 1.6221...
logNormal(0, 0.5); // 1.2840...

Omit.logNormal


multinomial: (n, weights) => number[]

Defined in: src/global/distributions.ts:380

Counts per category, summing to n.

number

ArrayLike<number>

number[]

multinomial(100, [1, 3, 6]); // [ 9, 31, 60 ]

Omit.multinomial


nanoid: (size, options) => string

Defined in: src/namespace/index.ts:40

A nanoid: 21 URL-safe characters by default. Drop-in for the nanoid package.

number = 21

NanoidOptions = {}

string

nanoid(); // "V1StGXR8_Z5jdHi6B-myT"
nanoid(10); // "IRFa-VaY2b"
nanoid(12, { alphabet: "0123456789abcdef" }); // "3f7a1c05e2b8"

Omit.nanoid


negativeBinomial: (r, p) => number

Defined in: src/global/distributions.ts:338

The number of failures before the r-th success.

number

number

number

negativeBinomial(3, 0.5); // 4

Omit.negativeBinomial


normal: (mean, sd) => number

Defined in: src/global/distributions.ts:24

One Gaussian draw.

number = 0

number = 1

number

normal(); // 0.4837... mean 0, sd 1
normal(100, 15); // 92.61... an IQ-shaped draw

Omit.normal


onCircle: (radius) => Point

Defined in: src/geometry.ts:60

A uniform point on the circumference of a circle.

number = 1

Point

onCircle(100); // [ -70.7, 70.7 ] always exactly 100 from the origin

Omit.onCircle


oneIn: (n) => boolean

Defined in: src/global/numbers.ts:114

true with probability 1 / n.

number

boolean

oneIn(20); // a critical hit on a d20

Omit.oneIn


onSphere: (radius, dimensions) => Point

Defined in: src/geometry.ts:94

A uniform point on the surface of a sphere.

number = 1

number = 3

Point

onSphere(1); // [ 0.267, -0.534, 0.801 ]
onSphere(2, 4); // a point on a 4-dimensional sphere of radius 2

Omit.onSphere


otp: (digits, options) => string

Defined in: src/namespace/index.ts:43

A numeric one-time code. Leading zeros are preserved.

number = 6

TokenOptions = {}

string

otp(); // "047215" six digits, leading zero kept
otp(8); // "90114862"

Omit.otp


pareto: (shape, scale) => number

Defined in: src/global/distributions.ts:173

One Pareto draw: the heavy-tailed shape behind the 80/20 rule.

number

number = 1

number

pareto(1.16); // 1.8721... scale 1 by default

Omit.pareto


password: (length, options) => string

Defined in: src/namespace/index.ts:44

A random password. With requireEach the result holds at least one character from every enabled class, then gets shuffled so their positions are random.

number = 16

PasswordOptions = {}

string

password(); // "vK8mQ2xL9pT4nR7c"
password(24, { symbols: true, requireEach: true });
password(12, { uppercase: false, symbols: false });

Omit.password


pastDate: (days) => Date

Defined in: src/time.ts:40

A Date within the last days (default 7).

number = 7

Date

pastDate(); // some time in the last week
pastDate(365); // some time in the last year

Omit.pastDate


permutation: (n) => number[]

Defined in: src/global/collections.ts:172

A shuffled [0, n), for permuting something you index yourself.

number

number[]

permutation(5); // [ 3, 0, 4, 1, 2 ]

Omit.permutation


pick: <T>(items) => T

Defined in: src/global/collections.ts:15

One element. Throws when the collection is empty.

T

Collection<T>

T

pick(["rock", "paper", "scissors"]); // "paper"
pick("abcdef"); // "d"
pick(new Set([1, 2, 3])); // 2

Omit.pick


pickEntry: <K, V>(target) => [K, V]

Defined in: src/global/collections.ts:66

One [key, value] pair of a plain object or Map.

K extends string | number | symbol

V

Record<K, V> | Map<K, V>

[K, V]

pickEntry({ a: 1, b: 2 }); // [ "b", 2 ]

Omit.pickEntry


pickIndex: <T>(items) => number

Defined in: src/global/collections.ts:40

The index of one element, rather than the element itself.

T

Collection<T>

number

pickIndex(["a", "b", "c"]); // 2

Omit.pickIndex


pickKey: <K, V>(target) => K

Defined in: src/global/collections.ts:52

One key of a plain object or Map.

K extends string | number | symbol

V

Record<K, V> | Map<K, V>

K

pickKey({ small: 1, medium: 2, large: 3 }); // "medium"

Omit.pickKey


pickValue: <K, V>(target) => V

Defined in: src/global/collections.ts:249

A uniformly chosen value of a plain object or Map.

K extends string | number | symbol

V

Record<K, V> | Map<K, V>

V

pickValue({ a: 1, b: 2, c: 3 }); // 3

Omit.pickValue


poisson: (lambda) => number

Defined in: src/global/distributions.ts:313

The number of events in one interval, given a mean rate.

number

number

poisson(4); // 3

Omit.poisson


random: () => number

Defined in: src/global/numbers.ts:12

A double in [0, 1). The Math.random drop-in.

number

random(); // 0.7401962...

Omit.random


Random: typeof Random

Defined in: src/namespace/index.ts:54

Omit.Random


range: (start, stop?, step?) => number

Defined in: src/global/numbers.ts:66

Python’s randrange: a member of [start, stop) stepping by step.

number

number

number

number

range(10); // 7 one argument is the upper bound
range(5, 10); // 8
range(0, 100, 5); // 45 multiples of five only

Omit.range


RansuError: typeof RansuError

Defined in: src/namespace/index.ts:56

Omit.RansuError


rayleigh: (scale) => number

Defined in: src/global/distributions.ts:198

One Rayleigh draw: the length of a 2D Gaussian vector.

number = 1

number

rayleigh(); // 1.1774...

Omit.rayleigh


reservoir: <T>(items, k) => T[]

Defined in: src/global/collections.ts:122

k elements from an iterable of unknown length, in one pass.

T

Iterable<T>

number

T[]

function* lines() {
yield "first";
yield "second";
yield "third";
}
// Nothing is buffered, so the source may be far larger than memory.
reservoir(lines(), 2); // [ "third", "first" ]

Omit.reservoir


rgb: (options) => [number, number, number, number]

Defined in: src/color.ts:115

[red, green, blue, alpha], channels 0 to 255 and alpha 0 to 1.

ColorOptions = {}

[number, number, number, number]

rgb(); // [ 62, 129, 214, 1 ]
rgb({ alpha: [0.2, 0.8] }); // [ 200, 41, 96, 0.57 ]

Omit.rgb


rollout: (key, percent, salt?) => boolean

Defined in: src/hash.ts:95

Whether key falls inside a percent rollout, where percent is a fraction in [0, 1]. Growing the percentage only ever adds keys, never moves one out.

Seed

number

Seed

boolean

rollout("user-42", 0.1); // false, not in the first 10%
rollout("user-42", 0.5); // true, and it stays true as the rollout widens

Omit.rollout


sample: <T>(items, k) => T[]

Defined in: src/global/collections.ts:92

k distinct elements, in random order.

T

Collection<T>

number

T[]

sample([1, 2, 3, 4, 5], 3); // [ 4, 1, 5 ]

Omit.sample


sampleIntegers: (count, min, max) => number[]

Defined in: src/global/numbers.ts:227

count distinct integers in [min, max], without materialising the range.

number

number

number

number[]

sampleIntegers(6, 1, 49); // [ 12, 3, 41, 28, 7, 33 ]
sampleIntegers(3, 0, 1_000_000_000); // fine: the range is never built

Omit.sampleIntegers


seed: (value) => void

Defined in: src/global/index.ts:5

Make every top-level function deterministic from here on.

Seed

void

seed(42);
integer(1, 6); // 3
seed(42);
integer(1, 6); // 3 again

Omit.seed


SeedSequence: typeof SeedSequence

Defined in: src/namespace/index.ts:55

Omit.SeedSequence


setState: (state) => void

Defined in: src/global/index.ts:5

Rewind or fast-forward the global stream to a saved snapshot.

EngineState

void

seed(1);
setState(getState()); // a no-op, but this is the shape

Omit.setState


shuffle: <T>(items) => T[]

Defined in: src/global/collections.ts:147

A shuffled copy. The input is untouched.

T

Collection<T>

T[]

shuffle([1, 2, 3, 4, 5]); // [ 3, 1, 5, 2, 4 ]

Omit.shuffle


shuffleInPlace: <T>(items) => T[]

Defined in: src/global/collections.ts:160

Fisher–Yates in place: the only mutating shuffle.

T

T[]

T[]

const deck = [1, 2, 3, 4, 5];
shuffleInPlace(deck); // deck itself is reordered and returned

Omit.shuffleInPlace


shuffleString: (value) => string

Defined in: src/global/collections.ts:184

The characters of a string in random order, by code point.

string

string

shuffleString("ransu"); // "nusar"

Omit.shuffleString


sign: () => number

Defined in: src/global/numbers.ts:126

-1 or 1.

number

sign() * 5; // -5

Omit.sign


stream: () => Generator<number, never, unknown>

Defined in: src/global/numbers.ts:214

An endless stream of doubles in [0, 1).

Generator<number, never, unknown>

for (const value of stream()) {
if (value > 0.99) break;
}

Omit.stream


string: (length, alphabet?) => string

Defined in: src/global/strings.ts:16

A random string over alphabet (default alphanumeric).

number

string | ArrayLike<string>

string

string(12); // "yYwec14FcPKc"
string(6, "ABCDEF0123456789"); // "3E9A1C"
string(4, ["cat", "dog"]); // "dogcatdogdog"

Omit.string


studentT: (df) => number

Defined in: src/global/distributions.ts:101

One Student’s t draw: a normal with heavier tails.

number

number

studentT(5); // -0.8412...

Omit.studentT


subset: <T>(items, p) => T[]

Defined in: src/global/collections.ts:266

Each element kept independently with probability p.

The result has no fixed length: it is a coin flip per element, so the size varies around items.length * p. Order is preserved.

T

Collection<T>

number

T[]

subset([1, 2, 3, 4, 5, 6], 0.5); // [ 1, 4, 5 ]

Omit.subset


takeOut: <T>(items) => T

Defined in: src/global/collections.ts:135

Remove one random element and return it. Mutates the array.

T

T[]

T

const deck = ["A", "K", "Q", "J"];
takeOut(deck); // "Q", and deck is now [ "A", "K", "J" ]

Omit.takeOut


token: (bytes, options) => string

Defined in: src/namespace/index.ts:42

A URL-safe secret token with bytes bytes of entropy. CSPRNG-backed.

number = 32

TokenOptions = {}

string

token(); // "xK3n_9QpZ..." 32 bytes as base64url
token(16); // shorter, still from the platform CSPRNG

Omit.token


triangular: (min, max, mode?) => number

Defined in: src/global/distributions.ts:211

One draw from a triangle, with an optional peak.

number

number

number

number

triangular(0, 10); // 4.7213... peak at the midpoint
triangular(0, 10, 9); // 7.8102... peak at 9

Omit.triangular


tryPick: <T>(items) => T | undefined

Defined in: src/global/collections.ts:28

One element, or undefined when the collection is empty.

T

Collection<T>

T | undefined

tryPick([]); // undefined
tryPick(["a", "b"]); // "a"

Omit.tryPick


ulid: UlidApi

Defined in: src/namespace/index.ts:41

A ULID: 26 characters of Crockford base32, time-ordered.

48 bits of millisecond timestamp then 80 bits of randomness, encoded so that lexicographic order is time order. Shorter than a UUID and case-insensitive, with no dashes to strip.

const id = ulid(); // "01K39XQZP4W8YHN2VBTKD7A3RM"
ulid.timestamp(id); // 1756890764019
// Sorts in creation order as a plain string.
ulid() < ulid(); // true

Omit.ulid


unicodeRanges: object

Defined in: src/namespace/index.ts:47

The named Unicode blocks the string functions accept.

readonly all: readonly [readonly [0, 1114111]]

readonly arabic: readonly [readonly [1536, 1791]]

readonly arrows: readonly CodePointRange[] = ARROWS

readonly ascii: readonly CodePointRange[] = ASCII

readonly blockElements: readonly CodePointRange[] = BLOCKS

readonly bmp: readonly [readonly [0, 65535]]

readonly box: readonly CodePointRange[] = BOX

readonly braille: readonly CodePointRange[] = BRAILLE

readonly cjk: readonly CodePointRange[]

readonly currency: readonly CodePointRange[] = CURRENCY

readonly cyrillic: readonly CodePointRange[] = CYRILLIC

readonly devanagari: readonly [readonly [2304, 2431]]

readonly emoji: readonly CodePointRange[] = EMOJI

readonly geometric: readonly CodePointRange[] = GEOMETRIC

readonly greek: readonly CodePointRange[] = GREEK

readonly hangul: readonly CodePointRange[] = HANGUL

readonly hebrew: readonly [readonly [1424, 1535]]

readonly hiragana: readonly CodePointRange[] = HIRAGANA

readonly kana: readonly CodePointRange[]

readonly kanji: readonly CodePointRange[] = KANJI

readonly katakana: readonly CodePointRange[] = KATAKANA

readonly latin: readonly CodePointRange[] = LATIN

readonly latin1: readonly [readonly [32, 126], readonly [160, 255]]

readonly latinExtended: readonly [readonly [256, 591]]

readonly math: readonly CodePointRange[] = MATH

readonly printable: readonly CodePointRange[]

readonly punctuation: readonly CodePointRange[] = PUNCTUATION

readonly symbols: readonly CodePointRange[]

readonly thai: readonly [readonly [3584, 3711]]

import { char, unicodeRanges } from "ransu";
Object.keys(unicodeRanges); // "printable", "latin", "hiragana", ...
char({ blocks: "hiragana" });
char({ blocks: ["hiragana", "katakana"] });

Omit.unicodeRanges


unitVector: (dimensions) => Point

Defined in: src/geometry.ts:30

A uniform direction in dimensions dimensions, as a unit vector.

Normalised Gaussians, which is the only construction that stays uniform on the sphere in every dimension. Picking each coordinate uniformly and normalising concentrates points toward the corners of the cube.

number = 2

Point

unitVector(); // [ -0.6018, 0.7986 ] length 1
unitVector(3); // [ 0.2673, -0.5345, 0.8018 ]

Omit.unitVector


uuid: UuidApi

Defined in: src/namespace/index.ts:39

A UUID, in every version RFC 9562 defines.

Calling it gives a v4; every version and helper hangs off it. Names and argument order match the uuid package, so it is a drop-in for that.

uuid(); // "39817b65-27b9-45d0-9b51-315d530a3211" a v4
uuid.v4(); // the same thing, spelled out
// Time-ordered, so it sorts by creation time in a database index.
uuid.v7(); // "0198f2a4-1c05-7e2b-8f31-9d4a7c0e15b3"
// Name-based: the same name always gives the same UUID.
uuid.v5("example.com", uuid.NAMESPACE.DNS);
uuid.validate(uuid()); // true
uuid.version(uuid.v7()); // 7
uuid.timestamp(uuid.v7()); // 1756890764019
uuid.NIL; // "00000000-0000-0000-0000-000000000000"
uuid.MAX; // "ffffffff-ffff-ffff-ffff-ffffffffffff"

Omit.uuid


vonMises: (mu, kappa) => number

Defined in: src/global/distributions.ts:249

One angle in (-pi, pi]. The circular analogue of a normal.

number = 0

number = 1

number

vonMises(); // 0.3218...
vonMises(0, 10); // 0.0782... a larger kappa concentrates near mu

Omit.vonMises


weibull: (shape, scale) => number

Defined in: src/global/distributions.ts:186

One Weibull draw, used for time until failure.

number

number = 1

number

weibull(1.5); // 0.7943...
weibull(1.5, 100); // 79.43...

Omit.weibull


weightedPick: <T>(items, weights) => T

Defined in: src/global/collections.ts:197

One element, with probability proportional to its weight.

T

Collection<T>

ArrayLike<number>

T

// "common" ten times as often as "rare".
weightedPick(["common", "rare"], [10, 1]); // "common"

Omit.weightedPick


weightedSample: <T>(items, weights, k) => T[]

Defined in: src/global/collections.ts:212

k distinct elements, drawn in proportion to their weights.

T

Collection<T>

ArrayLike<number>

number

T[]

weightedSample(["a", "b", "c"], [1, 3, 6], 2); // [ "c", "b" ]

Omit.weightedSample


weightedTable: <T>(items, weights) => object

Defined in: src/global/collections.ts:233

A reusable weighted sampler, O(1) per draw.

Build one when the same weights are drawn from repeatedly; weightedPick is a linear scan and is the better choice for a one-off.

T

Collection<T>

ArrayLike<number>

object

pick(): T

T

const loot = weightedTable(["common", "rare", "epic"], [90, 9, 1]);
loot.pick(); // "common"
loot.pick(); // "common"

Omit.weightedTable


zipf: (s, n) => number

Defined in: src/global/distributions.ts:367

A rank in 1..n, following the power law behind word frequency.

number

number

number

zipf(1.2, 1000); // 3

Omit.zipf

clone(): Random

Defined in: src/namespace/index.ts:61

An independent copy of the global stream, positioned where it is now.

Random

Omit.clone


split(n): Random[]

Defined in: src/namespace/index.ts:73

n independent generators derived from the global stream.

number

Random[]

Omit.split