@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
73 lines • 2.83 kB
JavaScript
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
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"); }
export function HashText(text) {
var hash = 0;
for (var 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();
export var RNGEngine = /*#__PURE__*/function () {
function RNGEngine(inputSeed) {
_classCallCheck(this, RNGEngine);
_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)));
}
return _createClass(RNGEngine, [{
key: "next",
value: function next() {
_classPrivateFieldSet(_value, this, _classPrivateFieldGet(_value, this) * 16807 % 2147483647);
return _classPrivateFieldGet(_value, this) / 2147483647;
}
}, {
key: "call",
value: function call() {
return this.next();
}
}, {
key: "reset",
value: function reset() {
_classPrivateFieldSet(_value, this, _assertClassBrand(_RNGEngine_brand, this, _normalizeSeed).call(this, _classPrivateFieldGet(_seed, this)));
}
}], [{
key: "create",
value: function create(seed) {
var engine = new RNGEngine(seed);
return function () {
return engine.next();
};
}
}]);
}();
function _normalizeSeed(seed) {
var value = seed % 2147483647;
if (value <= 0) {
value += 2147483646;
}
return value;
}
;
export function RNG(seed) {
return RNGEngine.create(seed);
}
;