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
const secure = Random.secure();
secure.token(); // e.g. "Kz0v...": 32 random bytes as base64url, for sessions and CSRF
secure.uuid(); // an unpredictable v4 UUIDExtends
RandomBase
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
luck | readonly | number | How much the outcome methods favour good results: 0 is neutral, negative is unlucky. |
Methods
boolean()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
chance | number | 0.5 | The probability of true, from 0 to 1 (default 0.5). |
Returns
boolean
The random boolean.
Example
new Random("x").boolean(0.75); // 75% trueThrows
When chance is outside 0..1. A percentage such as 50 is an error, not "always true".
Inherited from
RandomBase.booleanbytes()
bytes(count: number): Uint8Array;Defined in: core/random-base.ts:330
Random bytes, four per word, most significant first. Fair: ignores luck.
Parameters
| Parameter | Type | Description |
|---|---|---|
count | number | How many bytes. |
Returns
Uint8Array
The bytes.
Example
new Random("x").bytes(4); // => Uint8Array [ 213, 7, 88, 140 ]Throws
When count is not a non-negative integer.
Inherited from
RandomBase.bytesdate()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
after | string | number | Date | 0 | One bound (default: the epoch). |
before | string | number | Date | ... | The other bound (default: now). |
Returns
Date
The random date.
Example
new Random("x").date("2020-01-01", "2020-12-31"); // => a date in 2020Throws
When a bound is not a valid date or the range is wider than 2^53 ms.
Inherited from
RandomBase.dateexponential()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
rate | number | 1 | Events per unit, greater than 0 (default 1). |
Returns
number
The waiting time.
Example
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
RandomBase.exponentialfloat()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
min | number | 0 | One bound (default 0). |
max | number | 1 | The other bound (default 1). |
Returns
number
The random float.
Example
new Random("x").float(10, 20); // => a number in [10, 20)Throws
When a bound is not finite.
Inherited from
RandomBase.floatfork()
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
const child = Random.secure({ luck: 1 }).fork();from()
from(source)
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
| Parameter | Type | Description |
|---|---|---|
source | readonly T[] | The array to pick from. |
Returns
T | undefined
An element, or undefined when the array is empty.
Example
new Random("x").from([10, 20, 30]); // => 10, 20 or 30Inherited from
RandomBase.fromfrom(source)
from(source: string): string | undefined;Defined in: core/random-base.ts:177
A random character (code point) of a string. Fair: ignores luck.
Parameters
| Parameter | Type | Description |
|---|---|---|
source | string | The string to pick from. |
Returns
string | undefined
A character, or undefined when the string is empty.
Example
new Random("x").from("abc"); // => "a", "b" or "c"Inherited from
RandomBase.fromfrom(source)
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
| Parameter | Type | Description |
|---|---|---|
source | Readonly<Record<string, T>> | The object whose values to pick from. |
Returns
T | undefined
A value, or undefined when the object has none.
Example
new Random("x").from({ a: 1, b: 2 }); // => 1 or 2Inherited from
RandomBase.fromid()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
length | number | 10 | How many characters (default 10). |
alphabet | string | ALPHANUMERIC | The characters to draw from (default: letters and digits). |
Returns
string
The string.
Example
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
RandomBase.idint()
int(min, max)
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
| Parameter | Type | Description |
|---|---|---|
min | number | One bound. |
max | number | The other bound. |
Returns
number
The random integer.
Example
new Random("x").int(1, 6); // => 1, 2, 3, 4, 5 or 6Throws
When the range holds no integer, is not finite or is wider than 2^53.
Inherited from
RandomBase.intint(max)
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
| Parameter | Type | Description |
|---|---|---|
max | number | The other bound; the range starts at 0. |
Returns
number
The random integer.
Example
new Random("x").int(9); // => 0, 1, ... or 9Throws
When the range holds no integer, is not finite or is wider than 2^53.
Inherited from
RandomBase.intnext()
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
new Random("x").next(); // => a number in [0, 1)Inherited from
RandomBase.nextnormal()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
mean | number | 0 | The centre of the curve (default 0). |
deviation | number | 1 | How wide it is (default 1); 0 always returns the mean. |
Returns
number
The number.
Example
new Random("x").normal(100, 15); // => e.g. 108.4Throws
When mean or deviation is not finite, or deviation is negative.
Inherited from
RandomBase.normalpop()
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
| Parameter | Type | Description |
|---|---|---|
array | T[] | The array to take an element from. |
Returns
T | undefined
The removed element, or undefined when the array is empty.
Example
const deck = [1, 2, 3];
new Random("x").pop(deck); // => one of them, now missing from `deck`Inherited from
RandomBase.poproll()
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
| Parameter | Type | Description |
|---|---|---|
notation | string | The dice notation. |
Returns
number
The total.
Example
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
RandomBase.rollsample()
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
| Parameter | Type | Description |
|---|---|---|
items | readonly T[] | What to sample from. |
count | number | How many, from 0 up to items.length. |
Returns
T[]
The chosen items.
Example
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
RandomBase.sampleshuffle()
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
| Parameter | Type | Description |
|---|---|---|
array | readonly T[] | The items to shuffle. |
Returns
T[]
A new, shuffled array.
Example
new Random("x").shuffle([1, 2, 3, 4]); // => e.g. [3, 1, 4, 2]Inherited from
RandomBase.shuffletoken()
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
| Parameter | Type | Default value | Description |
|---|---|---|---|
bytes | number | 32 | How many random bytes (default 32). |
Returns
string
The token.
Example
Random.secure().token(); // => "kZ3vQ...": 43 characters
Random.secure().token(16); // => 22 charactersThrows
When bytes is not a non-negative integer.
uuid()
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
new Random("x").uuid(); // => "3f2b8c1e-9a47-4d0e-8b5a-6c1d2e7f9a03" (the same for this seed)Inherited from
RandomBase.uuidweighted()
weighted(items, weights)
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
| Parameter | Type | Description |
|---|---|---|
items | readonly T[] | What to pick from. |
weights | readonly number[] | One weight per item: finite and not negative, adding up to more than 0. |
Returns
T
The picked item.
Example
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
RandomBase.weightedweighted(table)
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
| Parameter | Type | Description |
|---|---|---|
table | Readonly<Record<K, number>> | Each key with its weight. |
Returns
K
The picked key.
Example
new Random("x").weighted({ common: 80, rare: 15, epic: 5 }); // => "common", "rare" or "epic"Throws
For a table it cannot use.
Inherited from
RandomBase.weighted