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)
- Handle primitive types first - they can be returned directly.
- Use a WeakMap to track visited objects for circular reference detection.
- Check for special object types: Date, RegExp, Map, Set.
- For arrays and objects, recursively clone each element/property.
- Use
Object.create(Object.getPrototypeOf(obj))to preserve prototype chain.
Topics
- Objects
Asked at
Google · Meta · Apple · Stripe
