Random
import Random, { SeededRandom } from "@arclockproject/common/library/Random";
For examples and live demos, see the Random guide.
Random
Instance of SeededRandom · default export
Shared unseeded SeededRandom, backed by Math.random(). Results differ on every run.
Example
import Random from "@arclockproject/common/library/Random";
Random.rangeInt(0, 6) + 1; // dice roll, 1 to 6
SeededRandom
Class
class SeededRandom
Random helpers that can be seeded. With a seed, the same seed always gives the same sequence of results, which is useful for repeatable worlds or tests.
For unseeded use, import the default Random instance instead.
Constructor
new SeededRandom(seed?: string)
Creates a generator. The same seed always gives the same numbers, in the same order.
Parameters
seed?(string) — Any string. Without one (or with""),Math.random()is used and results are not repeatable.
Example
const a = new SeededRandom("level-1");
const b = new SeededRandom("level-1");
a.rangeInt(0, 100) === b.rangeInt(0, 100); // true
SeededRandom.random()
SeededRandom.random(): number
Returns the next random float, from 0 up to but not including 1.
Every call moves a seeded generator forward, so calling it once and ignoring the result is a way to skip ("re-roll") a value.
Returns number — Float in the range [0, 1).
SeededRandom.rangeInt()
SeededRandom.rangeInt(start: number, end: number): number
Returns a random integer from start up to but not including end.
Parameters
start(number) — Lowest possible result.end(number) — Upper limit, never returned.
Returns number — Integer in the range [start, end).
Example
Random.rangeInt(0, 5); // 0, 1, 2, 3 or 4
SeededRandom.rangeFloat()
SeededRandom.rangeFloat(start: number, end: number): number
Returns a random float from start up to but not including end.
Parameters
start(number) — Lowest possible result.end(number) — Upper limit, never returned.
Returns number — Float in the range [start, end).
Example
Random.rangeFloat(0, 5); // e.g. 3.666, never 5
SeededRandom.fromArray()
SeededRandom.fromArray<k>(array: k[]): k
Picks a random element of array.
Parameters
array(k[]) — Array to pick from. If it is empty,undefinedis returned.
Returns k — One of the elements.
Example
Random.fromArray(["rock", "paper", "scissors"]); // e.g. "paper"
SeededRandom.fromArrayIndex()
SeededRandom.fromArrayIndex<k>(array: k[]): number
Picks a random index of array.
Parameters
array(k[]) — Array to pick an index from.
Returns number — Integer from 0 up to but not including array.length.
Example
Random.fromArrayIndex(["rock", "paper", "scissors"]); // e.g. 2
SeededRandom.fromArrayWithIndex()
SeededRandom.fromArrayWithIndex<k>(array: k[]): [k, number]
Picks a random element of array together with its index.
Parameters
array(k[]) — Array to pick from.
Returns [k, number] — [element, index].
Example
Random.fromArrayWithIndex(["rock", "paper", "scissors"]); // e.g. ["scissors", 2]