All files / src/common clone-deep.ts

90.47% Statements 19/21
83.33% Branches 10/12
100% Functions 5/5
90.47% Lines 19/21

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                        2759x   1091x         1091x   32x     1059x       1059x 115x 79x 79x       944x 944x 3639x 3639x           68x 132x     68x 21x 21x 21x    
function deepCopy(obj: any) {
  // Check for immutable primitives
  // https://developer.mozilla.org/en-US/docs/Glossary/Primitive
  // string, number, bigint, boolean, undefined, symbol, and null.
  switch (typeof obj) {
    case 'string':
    case 'number':
    case 'bigint':
    case 'boolean':
    case 'undefined':
    case 'symbol':
    case 'function': // also don't attempt to "clone" a function
      return obj;
  }
  Iif (obj === null) {
    return obj;
  }
 
  // Support deep cloning TypedArrays like Uint8Array
  if (ArrayBuffer.isView(obj)) {
    // Womp: https://github.com/microsoft/TypeScript/issues/15402
    return (obj as any).slice();
  }
 
  Iif (obj instanceof Date) {
    return new Date(obj);
  }
 
  if (obj instanceof Array) {
    return obj.reduce((arr, item, i) => {
      arr[i] = deepCopy(item);
      return arr;
    }, []);
  }
 
  if (obj instanceof Object) {
    return Object.keys(obj as object).reduce((newObj: Record<string, any>, key) => {
      newObj[key] = deepCopy(obj[key]);
      return newObj;
      // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
    }, Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)));
  }
}
 
export function cloneDeep<T>(value: T): T {
  return deepCopy(value) as T;
}
 
export function omit<T, K extends keyof T>(obj: T, prop: K): Omit<T, K> {
  const clone = cloneDeep<T>(obj);
  delete clone[prop];
  return clone;
}