All files / util/src/json-clone cloneBinary.ts

100% Statements 26/26
100% Branches 5/5
100% Functions 1/1
100% Lines 20/20

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 321x   1x 1x               1x 3878x 3782x 921x 921x 921x 921x 2861x 1372x 1357x 1357x 1357x 1357x 3004x 3004x   1357x   1489x    
import {isUint8Array} from '@jsonjoy.com/buffers/lib/isUint8Array';
 
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 cloneBinary = <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(cloneBinary(obj[i]));
    return arr as unknown as T;
  } else if (typeof obj === 'object') {
    if (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] = cloneBinary((obj as any)[key]);
    }
    return newObject;
  }
  return obj;
};