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

100% Statements 23/23
100% Branches 4/4
100% Functions 1/1
100% Lines 18/18

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 291x 1x               1x 3849x 3754x 918x 918x 918x 918x 2836x 1351x 1351x 1351x 1351x 2990x 2990x   1351x   1485x    
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') {
    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;
};