@trap_stevo/rng
Version:
Unleash beautifully deterministic randomness with a seedable generator crafted for developers, artists, game designers, and procedural creators. Whether forging alien worlds, generating dynamic narratives, or craving control over chaos, this tool delivers
66 lines (65 loc) • 2.42 kB
JavaScript
;
function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
function HashText(text) {
let hash = 0;
for (let i = 0; i < text.length; i++) {
hash = (hash << 5) - hash + text.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
;
var _value = /*#__PURE__*/new WeakMap();
var _seed = /*#__PURE__*/new WeakMap();
var _RNGEngine_brand = /*#__PURE__*/new WeakSet();
class RNGEngine {
constructor(inputSeed) {
_classPrivateMethodInitSpec(this, _RNGEngine_brand);
_classPrivateFieldInitSpec(this, _value, void 0);
_classPrivateFieldInitSpec(this, _seed, void 0);
if (typeof seedInput === "string") {
_classPrivateFieldSet(_seed, this, HashText(seedInput));
} else if (typeof seedInput === "number") {
_classPrivateFieldSet(_seed, this, seedInput);
} else {
_classPrivateFieldSet(_seed, this, Math.floor(Math.random() * 2147483646) + 1);
}
_classPrivateFieldSet(_value, this, _assertClassBrand(_RNGEngine_brand, this, _normalizeSeed).call(this, _classPrivateFieldGet(_seed, this)));
}
next() {
_classPrivateFieldSet(_value, this, _classPrivateFieldGet(_value, this) * 16807 % 2147483647);
return _classPrivateFieldGet(_value, this) / 2147483647;
}
call() {
return this.next();
}
reset() {
_classPrivateFieldSet(_value, this, _assertClassBrand(_RNGEngine_brand, this, _normalizeSeed).call(this, _classPrivateFieldGet(_seed, this)));
}
static create(seed) {
const engine = new RNGEngine(seed);
return () => engine.next();
}
}
function _normalizeSeed(seed) {
let value = seed % 2147483647;
if (value <= 0) {
value += 2147483646;
}
return value;
}
;
function RNG(seed) {
return RNGEngine.create(seed);
}
;
module.exports = {
RNGEngine,
HashText,
RNG
};