All files / json-random/src util.ts

97.5% Statements 39/40
66.66% Branches 6/9
100% Functions 4/4
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 673x   3x   3x 3x 21x 28950x 28950x                                     3x 21x 21x 21x 21x   21x       3x 3x               3x 30x 26x 2x 2x 5x 2x 24x 3x 3x 3x 3x 3x 4x 4x   3x   21x    
import {isUint8Array} from '@jsonjoy.com/buffers/lib/isUint8Array';
 
const random = Math.random;
 
export const rnd =
  (seed = 123456789) =>
  () => {
    seed = (seed * 48271) % 2147483647;
    return (seed - 1) / 2147483646;
  };
 
/**
 * 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.
 */
export const deterministic = <T>(rndSeed: number | (() => number), code: () => T): T => {
  const isNative = Math.random === random;
  Math.random = typeof rndSeed === 'function' ? rndSeed : rnd(Math.round(rndSeed));
  try {
    return code();
  } finally {
    if (isNative) Math.random = random;
  }
};
 
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.
 */
export const clone = <T = unknown>(obj: T): T => {
  if (!obj) return obj;
  if (isArray(obj)) {
    const arr: unknown[] = [];
    const length = obj.length;
    for (let i = 0; i < length; i++) arr.push(clone(obj[i]));
    return arr as unknown as T;
  } else if (typeof obj === 'object') {
    Iif (isUint8Array(obj)) return new Uint8Array(obj) as unknown as T;
    const keys = objectKeys(obj!);
    const length = keys.length;
    const newObject: any = {};
    for (let i = 0; i < length; i++) {
      const key = keys[i];
      newObject[key] = clone((obj as any)[key]);
    }
    return newObject;
  }
  return obj;
};