UNPKG

@kobayami/random

Version:

An LCG random number generator that resembles the behavior of java.util.random

33 lines (32 loc) 1.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Random = void 0; const guards_1 = require("@kobayami/guards"); class Random { constructor(seed) { seed = guards_1.presentOrElse(seed, () => BigInt((Math.random() * 0x100000000) ^ 0)); this.seed = (seed ^ a) & mask; } nextRandom32Bit() { this.seed = (this.seed * a + c) & mask; return Number(this.seed >> shrBits); } random(startOrEnd, end) { return this._random(startOrEnd, end); } _random(startOrEnd, end) { const start = end === undefined ? 0 : guards_1.assertPresent(startOrEnd, 0); end = guards_1.assertPresent(end, guards_1.assertPresent(startOrEnd, 1)); return (this.nextRandom32Bit() / 0x100000000) * (end - start) + start; } randomInt(startOrEnd, end) { if (end === undefined && startOrEnd === undefined) return this.nextRandom32Bit() ^ 0; return this._random(startOrEnd, end) ^ 0; } } exports.Random = Random; const a = 25214903917n; const c = 11n; const mask = 0xffffffffffffn; const shrBits = 16n;