UNPKG

@jsonjoy.com/json-random

Version:

Random JSON generation, structured JSON by schema generation, no dependencies.

72 lines 2.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.clone = exports.deterministic = exports.rnd = void 0; const isUint8Array_1 = require("@jsonjoy.com/buffers/lib/isUint8Array"); const random = Math.random; const rnd = (seed = 123456789) => () => { seed = (seed * 48271) % 2147483647; return (seed - 1) / 2147483646; }; exports.rnd = rnd; /** * Executes code in a callback *deterministically*: the `Math.random()` function * is mocked for the duration of the callback. * * Example: * * ```js * deterministic(123, () => { * return Math.random() + 1; * }); * ``` * * @param rndSeed A seed number or a random number generator function. * @param code Code to execute deterministically. * @returns Return value of the code block. */ const deterministic = (rndSeed, code) => { const isNative = Math.random === random; Math.random = typeof rndSeed === 'function' ? rndSeed : (0, exports.rnd)(Math.round(rndSeed)); try { return code(); } finally { if (isNative) Math.random = random; } }; exports.deterministic = deterministic; const { isArray } = Array; const objectKeys = Object.keys; /** * Creates a deep clone of any JSON-like object. * * @param obj Any plain POJO object. * @returns A deep copy of the object. */ const clone = (obj) => { if (!obj) return obj; if (isArray(obj)) { const arr = []; const length = obj.length; for (let i = 0; i < length; i++) arr.push((0, exports.clone)(obj[i])); return arr; } else if (typeof obj === 'object') { if ((0, isUint8Array_1.isUint8Array)(obj)) return new Uint8Array(obj); const keys = objectKeys(obj); const length = keys.length; const newObject = {}; for (let i = 0; i < length; i++) { const key = keys[i]; newObject[key] = (0, exports.clone)(obj[key]); } return newObject; } return obj; }; exports.clone = clone; //# sourceMappingURL=util.js.map