Skip to content

SecureRandom ​

Import from
@gabreusi/hyrax
Examples
Run, answers asserted

Defined in: core/secure-random.ts:32

A generator backed by crypto.getRandomValues, for ids, tokens and anything an attacker must not be able to predict. It has the same methods as Random, but no seed and no state: it cannot be replayed, by design. Create it with Random.secure.

It has no limit on how many permutations shuffle can reach, and it never falls back to Math.random: without crypto, creating one throws.

Example ​

ts
const secure = Random.secure();
secure.token(); // e.g. "Kz0v...": 32 random bytes as base64url, for sessions and CSRF
secure.uuid(); // an unpredictable v4 UUID

Extends ​

  • RandomBase

Properties ​

PropertyModifierTypeDescription
luckreadonlynumberHow much the outcome methods favour good results: 0 is neutral, negative is unlucky.

Methods ​

boolean() ​

ts
boolean(chance?: number): boolean;

Defined in: core/random-base.ts:147

true with the given probability. Affected by luck: at luck 1 a 50% check succeeds 75% of the time.

Parameters ​

ParameterTypeDefault valueDescription
chancenumber0.5The probability of true, from 0 to 1 (default 0.5).

Returns ​

boolean

The random boolean.

Example ​

ts
new Random("x").boolean(0.75); // 75% true

Throws ​

When chance is outside 0..1. A percentage such as 50 is an error, not "always true".

Inherited from ​

ts
RandomBase.boolean

bytes() ​

ts
bytes(count: number): Uint8Array;

Defined in: core/random-base.ts:330

Random bytes, four per word, most significant first. Fair: ignores luck.

Parameters ​

ParameterTypeDescription
countnumberHow many bytes.

Returns ​

Uint8Array

The bytes.

Example ​

ts
new Random("x").bytes(4);   // => Uint8Array [ 213, 7, 88, 140 ]

Throws ​

When count is not a non-negative integer.

Inherited from ​

ts
RandomBase.bytes

date() ​

ts
date(after?: string | number | Date, before?: string | number | Date): Date;

Defined in: core/random-base.ts:256

A date between after and before, both included, at millisecond resolution. The defaults are the Unix epoch and now, so pass both bounds for a reproducible result. Fair: ignores luck.

Parameters ​

ParameterTypeDefault valueDescription
afterstring | number | Date0One bound (default: the epoch).
beforestring | number | Date...The other bound (default: now).

Returns ​

Date

The random date.

Example ​

ts
new Random("x").date("2020-01-01", "2020-12-31");   // => a date in 2020

Throws ​

When a bound is not a valid date or the range is wider than 2^53 ms.

Inherited from ​

ts
RandomBase.date

exponential() ​

ts
exponential(rate?: number): number;

Defined in: core/random-base.ts:481

An exponentially distributed number: the waiting time between events that happen rate times per unit. The mean is 1 / rate. Fair: ignores luck.

Parameters ​

ParameterTypeDefault valueDescription
ratenumber1Events per unit, greater than 0 (default 1).

Returns ​

number

The waiting time.

Example ​

ts
new Random("x").exponential(2);   // => e.g. 0.31 (a mean of 0.5)

Throws ​

When rate is not a positive, finite number.

Inherited from ​

ts
RandomBase.exponential

float() ​

ts
float(min?: number, max?: number): number;

Defined in: core/random-base.ts:76

A float in [min, max): the result is never max. The bounds may be given in either order. Affected by luck.

Parameters ​

ParameterTypeDefault valueDescription
minnumber0One bound (default 0).
maxnumber1The other bound (default 1).

Returns ​

number

The random float.

Example ​

ts
new Random("x").float(10, 20);   // => a number in [10, 20)

Throws ​

When a bound is not finite.

Inherited from ​

ts
RandomBase.float

fork() ​

ts
fork(): SecureRandom;

Defined in: core/secure-random.ts:56

Another secure generator with the same luck. A secure generator has no seed, so there is nothing to derive the child from and no keys to pass.

Returns ​

SecureRandom

The new generator.

Example ​

ts
const child = Random.secure({ luck: 1 }).fork();

from() ​

from(source)

ts
from<T>(source: readonly T[]): T | undefined;

Defined in: core/random-base.ts:165

A random element of an array. Fair: ignores luck.

Type Parameters ​
Type Parameter
T
Parameters ​
ParameterTypeDescription
sourcereadonly T[]The array to pick from.
Returns ​

T | undefined

An element, or undefined when the array is empty.

Example ​
ts
new Random("x").from([10, 20, 30]);   // => 10, 20 or 30
Inherited from ​
ts
RandomBase.from

from(source)

ts
from(source: string): string | undefined;

Defined in: core/random-base.ts:177

A random character (code point) of a string. Fair: ignores luck.

Parameters ​
ParameterTypeDescription
sourcestringThe string to pick from.
Returns ​

string | undefined

A character, or undefined when the string is empty.

Example ​
ts
new Random("x").from("abc");   // => "a", "b" or "c"
Inherited from ​
ts
RandomBase.from

from(source)

ts
from<T>(source: Readonly<Record<string, T>>): T | undefined;

Defined in: core/random-base.ts:189

A random value of an object. Fair: ignores luck.

Type Parameters ​
Type Parameter
T
Parameters ​
ParameterTypeDescription
sourceReadonly<Record<string, T>>The object whose values to pick from.
Returns ​

T | undefined

A value, or undefined when the object has none.

Example ​
ts
new Random("x").from({ a: 1, b: 2 });   // => 1 or 2
Inherited from ​
ts
RandomBase.from

id() ​

ts
id(length?: number, alphabet?: string): string;

Defined in: core/random-base.ts:279

A random string of characters from alphabet. Not unique, and not secret unless the generator is a SecureRandom. Fair: ignores luck.

Parameters ​

ParameterTypeDefault valueDescription
lengthnumber10How many characters (default 10).
alphabetstringALPHANUMERICThe characters to draw from (default: letters and digits).

Returns ​

string

The string.

Example ​

ts
new Random("x").id();          // => e.g. "aZ3kQ9pLm0"
new Random("x").id(4, "01");   // => e.g. "1001"

Throws ​

When length is not a non-negative integer or the alphabet is empty.

Inherited from ​

ts
RandomBase.id

int() ​

int(min, max)

ts
int(min: number, max: number): number;

Defined in: core/random-base.ts:104

An integer between min and max, both included. With luck 0 it has no bias at all: it keeps the top bits of a word and draws again when the value falls outside the range. The bounds may be given in either order, and fractional bounds are rounded inward (1.2..2.8 means 2). Affected by luck.

Parameters ​
ParameterTypeDescription
minnumberOne bound.
maxnumberThe other bound.
Returns ​

number

The random integer.

Example ​
ts
new Random("x").int(1, 6);   // => 1, 2, 3, 4, 5 or 6
Throws ​

When the range holds no integer, is not finite or is wider than 2^53.

Inherited from ​
ts
RandomBase.int

int(max)

ts
int(max: number): number;

Defined in: core/random-base.ts:118

An integer between 0 and max, both included: int(6) is int(0, 6), and gives the same result for the same seed. A negative max counts down from 0.

Parameters ​
ParameterTypeDescription
maxnumberThe other bound; the range starts at 0.
Returns ​

number

The random integer.

Example ​
ts
new Random("x").int(9);   // => 0, 1, ... or 9
Throws ​

When the range holds no integer, is not finite or is wider than 2^53.

Inherited from ​
ts
RandomBase.int

next() ​

ts
next(): number;

Defined in: core/random-base.ts:56

A fair float in [0, 1) with 53 bits of precision, built from two words. It is the raw material of the other methods and is never affected by luck.

Returns ​

number

The float.

Example ​

ts
new Random("x").next();   // => a number in [0, 1)

Inherited from ​

ts
RandomBase.next

normal() ​

ts
normal(mean?: number, deviation?: number): number;

Defined in: core/random-base.ts:457

A normally distributed number (Box-Muller): a bell curve around mean. It uses four words per call and never takes log(0). Fair: ignores luck.

Parameters ​

ParameterTypeDefault valueDescription
meannumber0The centre of the curve (default 0).
deviationnumber1How wide it is (default 1); 0 always returns the mean.

Returns ​

number

The number.

Example ​

ts
new Random("x").normal(100, 15);   // => e.g. 108.4

Throws ​

When mean or deviation is not finite, or deviation is negative.

Inherited from ​

ts
RandomBase.normal

pop() ​

ts
pop<T>(array: T[]): T | undefined;

Defined in: core/random-base.ts:213

Removes a random element from array (mutating it) and returns it. Fair: ignores luck.

Type Parameters ​

Type Parameter
T

Parameters ​

ParameterTypeDescription
arrayT[]The array to take an element from.

Returns ​

T | undefined

The removed element, or undefined when the array is empty.

Example ​

ts
const deck = [1, 2, 3];
new Random("x").pop(deck);   // => one of them, now missing from `deck`

Inherited from ​

ts
RandomBase.pop

roll() ​

ts
roll(notation: string): number;

Defined in: core/random-base.ts:505

Rolls dice from a notation and adds them up. Terms are joined with + or -: each is NdM (N dice with M sides; N defaults to 1), optionally followed by khK or klK to keep the K highest or lowest dice, or a whole number. Spaces and case are ignored. Every die uses the generator's luck, so luck 1 on a 1d20 is exactly advantage.

Parameters ​

ParameterTypeDescription
notationstringThe dice notation.

Returns ​

number

The total.

Example ​

ts
new Random("x").roll("2d6+3");    // => 5 to 15
new Random("x").roll("4d6kh3");   // => the best three of four d6
new Random("x").roll("1d8+1d6-1");

Throws ​

For a notation it cannot read, or more than 1000 dice in total.

Inherited from ​

ts
RandomBase.roll

sample() ​

ts
sample<T>(items: readonly T[], count: number): T[];

Defined in: core/random-base.ts:425

count items chosen without repeating a position, in random order (a partial Fisher-Yates). It samples positions, not values: two equal items in the input can both come out. The input is left untouched. Fair: ignores luck.

Type Parameters ​

Type Parameter
T

Parameters ​

ParameterTypeDescription
itemsreadonly T[]What to sample from.
countnumberHow many, from 0 up to items.length.

Returns ​

T[]

The chosen items.

Example ​

ts
new Random("x").sample(["a", "b", "c", "d", "e"], 3);   // => e.g. ["d", "a", "e"]

Throws ​

When count is not a whole number between 0 and the number of items.

Inherited from ​

ts
RandomBase.sample

shuffle() ​

ts
shuffle<T>(array: readonly T[]): T[];

Defined in: core/random-base.ts:231

A shuffled copy of array (Fisher-Yates). With a seed every permutation is equally likely up to 34 elements (the engine has 128 bits of state); past that, use SecureRandom. The input is left untouched. Fair: ignores luck.

Type Parameters ​

Type Parameter
T

Parameters ​

ParameterTypeDescription
arrayreadonly T[]The items to shuffle.

Returns ​

T[]

A new, shuffled array.

Example ​

ts
new Random("x").shuffle([1, 2, 3, 4]);   // => e.g. [3, 1, 4, 2]

Inherited from ​

ts
RandomBase.shuffle

token() ​

ts
token(bytes?: number): string;

Defined in: core/secure-random.ts:75

A random string of bytes bytes as base64url with no padding (URL-safe), for session ids, CSRF tokens and API keys. 32 bytes give 43 characters and 256 bits of entropy. Never touched by luck.

Parameters ​

ParameterTypeDefault valueDescription
bytesnumber32How many random bytes (default 32).

Returns ​

string

The token.

Example ​

ts
Random.secure().token();     // => "kZ3vQ...": 43 characters
Random.secure().token(16);   // => 22 characters

Throws ​

When bytes is not a non-negative integer.


uuid() ​

ts
uuid(): string;

Defined in: core/random-base.ts:304

A version 4 UUID drawn from this generator, so it is reproducible for a given seed. Fair: ignores luck. Unpredictable only for a SecureRandom.

Returns ​

string

The UUID, in lowercase.

Example ​

ts
new Random("x").uuid();   // => "3f2b8c1e-9a47-4d0e-8b5a-6c1d2e7f9a03" (the same for this seed)

Inherited from ​

ts
RandomBase.uuid

weighted() ​

weighted(items, weights)

ts
weighted<T>(items: readonly T[], weights: readonly number[]): T;

Defined in: core/random-base.ts:362

Picks one item, in proportion to its weight: [80, 15, 5] picks the first item 80% of the time. Items with weight 0 are never picked. Affected by luck, which slides the pick toward the end of the list: with positive luck the later, rarer entries come up more often, so list items from the most common to the rarest.

Type Parameters ​
Type Parameter
T
Parameters ​
ParameterTypeDescription
itemsreadonly T[]What to pick from.
weightsreadonly number[]One weight per item: finite and not negative, adding up to more than 0.
Returns ​

T

The picked item.

Example ​
ts
new Random("x").weighted(["common", "rare", "epic"], [80, 15, 5]);
Throws ​

For a table it cannot use: mismatched lengths, no items, a bad weight or a zero (or overflowing) total.

Inherited from ​
ts
RandomBase.weighted

weighted(table)

ts
weighted<K extends string>(table: Readonly<Record<K, number>>): K;

Defined in: core/random-base.ts:376

Picks one key of an object, in proportion to its weight. Same rules as the array form. Note that JavaScript lists integer-like keys ("1", "2") first, whatever order you wrote them in.

Type Parameters ​
Type Parameter
K extends string
Parameters ​
ParameterTypeDescription
tableReadonly<Record<K, number>>Each key with its weight.
Returns ​

K

The picked key.

Example ​
ts
new Random("x").weighted({ common: 80, rare: 15, epic: 5 });  // => "common", "rare" or "epic"
Throws ​

For a table it cannot use.

Inherited from ​
ts
RandomBase.weighted

MIT License. Every example on these pages is type-checked against the built package, and the core ones are run.