Deep Clone Object

HardObjects25 min4 tests

Implement a deepClone function that creates a deep copy of an object.

Requirements

  • Clone nested objects and arrays
  • Handle circular references
  • Preserve object types (Date, RegExp, Map, Set)
  • Don't use JSON.parse/stringify

Example

const obj = { a: 1, b: { c: 2 } };
const clone = deepClone(obj);
clone.b.c = 99;
console.log(obj.b.c); // 2 (original unchanged)
Hints (5)
  1. Handle primitive types first - they can be returned directly.
  2. Use a WeakMap to track visited objects for circular reference detection.
  3. Check for special object types: Date, RegExp, Map, Set.
  4. For arrays and objects, recursively clone each element/property.
  5. Use Object.create(Object.getPrototypeOf(obj)) to preserve prototype chain.

Topics

  • Objects

Asked at

Google · Meta · Apple · Stripe

Loading the sandbox…

Join Us
blur