Function: random()
random(args
: { lix
: Pick
<Lix
, "sqlite"
| "db"
| "hooks"
>; }): number
Returns a random float between 0 (inclusive) and 1 (exclusive).
In deterministic mode, generates reproducible values using xorshift128+ PRNG
(the same algorithm used by V8/Chrome for Math.random()).
In normal mode, uses crypto.getRandomValues() for cryptographically secure randomness.
- Normal mode: Uses crypto.getRandomValues() for cryptographic quality
- Deterministic mode: Uses xorshift128+ PRNG (same as V8/Chrome's Math.random())
- Default seed: Uses
lix_id
value unless lix_deterministic_rng_seed
is set
- State persisted via
lix_deterministic_rng_state
key value
- Both modes return 53-bit precision floats for consistency
- For ID generation, consider uuidV7 or nanoId instead
Examples
const lix = await openLix();
const r1 = random({ lix }); // 0.823... (unpredictable)
const r2 = random({ lix }); // 0.156... (unpredictable)
const lix = await openLix({
keyValues: [{ key: "lix_deterministic_mode", value: { enabled: true } }]
});
const r1 = random({ lix }); // 0.318... (always same sequence)
const r2 = random({ lix }); // 0.937... (for same seed)
const r3 = random({ lix }); // 0.543...
// Random selection
const items = ["a", "b", "c", "d"];
const idx = Math.floor(random({ lix }) * items.length);
const selected = items[idx];
// Fisher-Yates shuffle
function shuffle<T>(array: T[], lix: Lix): T[] {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random({ lix }) * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
Parameters
Parameter | Type | Description |
---|
args | { lix : Pick <Lix , "sqlite" | "db" | "hooks" >; } | - |
args.lix | Pick <Lix , "sqlite" | "db" | "hooks" > | The Lix instance with sqlite and db connections |
Returns
number
Random float between 0 (inclusive) and 1 (exclusive) with 53-bit precision