All files / platform/core/src/utils structuredCloneWithFunctions.ts

89.47% Statements 17/19
75% Branches 6/8
100% Functions 1/1
89.47% Lines 17/19

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          2184x 1196x   988x         988x 52x       936x         936x 468x 468x 468x 988x   468x       468x 468x 468x 1144x   468x    
/**
 * Clones the object, incorporating functions as functions in the result.
 */
export function structuredCloneWithFunctions(obj, seen = new WeakMap()) {
  // Handle null, primitives, and functions
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  Iif (typeof obj === 'function') {
    return obj; // copy function by reference
  }
 
  // Handle circular references
  if (seen.has(obj)) {
    return seen.get(obj);
  }
 
  // Handle Date
  Iif (obj instanceof Date) {
    return new Date(obj.getTime());
  }
 
  // Handle Array
  if (Array.isArray(obj)) {
    const arrCopy = [];
    seen.set(obj, arrCopy);
    for (const item of obj) {
      arrCopy.push(structuredCloneWithFunctions(item, seen));
    }
    return arrCopy;
  }
 
  // Handle Object
  const copy = {};
  seen.set(obj, copy);
  for (const key of Object.keys(obj)) {
    copy[key] = structuredCloneWithFunctions(obj[key], seen);
  }
  return copy;
}