Skip to main content
InterviewHubPRO
Section Overview
Q531

Question 531 of 536

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

99%
JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

How do you implement a robust deepClone function handling circular references, Dates, RegExps, Sets, and Maps?

mid LevelCode ExampleFormsPerformanceHTTP & REST APIs

In Simple Words: A robust deep clone recursively duplicates nested objects and arrays while using a WeakMap to track visited object references to prevent infinite call stack overflows on circular structures, and explicitly reconstructs special types like Date, RegExp, Map, and Set.

Limitations of Naive Approaches

  • JSON.parse(JSON.stringify(obj)): Fails on circular references (throws TypeError), drops undefined, functions, and Symbol keys, converts Date objects to ISO strings, converts Map and Set to empty objects, and turns NaN/Infinity into null.
  • Object.assign() or spread { ...obj }: Shallow copies only top-level properties; nested references are shared.
  • structuredClone(obj): Native in modern browsers/Node.js 17+, but throws an error when trying to clone objects with function methods or DOM nodes.

Production Deep Clone Implementation

javascript
function deepClone(value, hash = new WeakMap()) {
  // 1. Return primitives and functions directly (immutable or copied by reference)
  if (value === null || typeof value !== 'object') {
    return value;
  }

  // 2. Handle Dates
  if (value instanceof Date) {
    return new Date(value.getTime());
  }

  // 3. Handle Regular Expressions
  if (value instanceof RegExp) {
    return new RegExp(value.source, value.flags);
  }

  // 4. Handle Circular References via WeakMap memoization
  if (hash.has(value)) {
    return hash.get(value);
  }

  // 5. Handle Sets
  if (value instanceof Set) {
    const cloneSet = new Set();
    hash.set(value, cloneSet);
    for (const item of value) {
      cloneSet.add(deepClone(item, hash));
    }
    return cloneSet;
  }

  // 6. Handle Maps
  if (value instanceof Map) {
    const cloneMap = new Map();
    hash.set(value, cloneMap);
    for (const [k, v] of value) {
      cloneMap.set(deepClone(k, hash), deepClone(v, hash));
    }
    return cloneMap;
  }

  // 7. Handle Arrays and Plain Objects preserving prototype
  const prototype = Object.getPrototypeOf(value);
  const cloneObj = Array.isArray(value) ? [] : Object.create(prototype);

  // Cache object BEFORE recursive descent to resolve circular references
  hash.set(value, cloneObj);

  // Copy own enumerable and Symbol properties
  const allKeys = [...Object.keys(value), ...Object.getOwnPropertySymbols(value)];
  for (const key of allKeys) {
    cloneObj[key] = deepClone(value[key], hash);
  }

  return cloneObj;
}

// Verification with Circular Reference & Special Types:
const original = {
  name: "Deep Copy Test",
  date: new Date(),
  pattern: /^[a-z]+$/gi,
  tags: new Set(["javascript", "node"]),
  metadata: new Map([["version", 1.0]]),
  details: { role: "Architect" }
};
// Add circular reference:
original.self = original;

const cloned = deepClone(original);
console.log(cloned !== original);               // true
console.log(cloned.details !== original.details); // true
console.log(cloned.self === cloned);             // true (Cycle handled perfectly!)
console.log(cloned.date instanceof Date);        // true
console.log(cloned.tags.has("javascript"));      // true