Microsoft Questions

Implement a deep clone function that handles objects, arrays, dates, and circular references.

MediumTechnicalJavaScript20-25 minutes

Model Answer

Deep cloning creates a completely independent copy of a data structure, including nested objects. The challenge is handling special types (Date, RegExp, Map, Set) and circular references that would cause infinite recursion.

Approaches

Recursive Clone with WeakMap for Cycles

Recursively traverse the object, using a WeakMap to track already-cloned objects and break circular references. Handle each type specifically.

function deepClone(obj, seen = new WeakMap()) {
  // Primitives and null
  if (obj === null || typeof obj !== 'object') return obj;

  // Circular reference check
  if (seen.has(obj)) return seen.get(obj);

  // Special types
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
  if (obj instanceof Map) {
    const map = new Map();
    seen.set(obj, map);
    obj.forEach((val, key) => map.set(deepClone(key, seen), deepClone(val, seen)));
    return map;
  }
  if (obj instanceof Set) {
    const set = new Set();
    seen.set(obj, set);
    obj.forEach(val => set.add(deepClone(val, seen)));
    return set;
  }

  // Arrays and plain objects
  const clone = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
  seen.set(obj, clone);

  for (const key of Reflect.ownKeys(obj)) {
    clone[key] = deepClone(obj[key], seen);
  }
  return clone;
}
Time: O(n) where n is total number of propertiesSpace: O(n) for the cloned structure + WeakMap

Common Mistakes

  • 1.Using JSON.parse(JSON.stringify()) which fails for Date, undefined, functions, and circular references
  • 2.Not handling circular references (infinite recursion)
  • 3.Forgetting that Date, RegExp, Map, Set need special handling
  • 4.Not preserving the prototype chain

Follow-up Questions

  • What are the trade-offs vs. using structuredClone()?
  • How would you handle cloning objects with getters and setters?
  • What about cloning objects with Symbol keys?