Deep Clone II
Problem statement
Implement deepClone, an advanced deep clone function that handles common JavaScript data types and circular references.
This is an advanced version of the classic Deep Clone problem. A complete production-grade clone is large, but this question focuses on the most important edge cases interviewers discuss.
Requirements
- Handle primitives, arrays, plain objects,
Date,RegExp,Map, andSet. - Clone symbol-keyed properties.
- Preserve circular references without causing infinite recursion.
- Functions can be returned by reference.
Example
const obj = { a: {} };
obj.a.b = obj;
const cloned = deepClone(obj);
cloned !== obj; // true
cloned.a.b === cloned; // true
Requirements & constraints
- Handle circular references.
- Do not use `structuredClone`.
- Functions may be returned by reference.
How to approach Deep Clone II
The strategy an interviewer expects you to reach for.
Deep clone II adds cycles and built-ins — the version that breaks after someone says “just use JSON.parse(JSON.stringify)”. Naive move JSON clone. Dates become strings, undefined/functions vanish, maps/sets die, cycles throw. Where it breaks Circular references recurse forever without a WeakMap of seen originals → clones. Date/Map/Set/RegExp need type-specific constructors. The fix Recurse with a WeakMap. On object enter, stash the new clone before walking children. Branch for Date/Map/Set/Array/plain object. Remember: WeakMap first (cycles), then special-case built-ins, then plain objects. Say this in the interview: I'd deep-clone with a WeakMap to break cycles, handle Date/Map/Set explicitly, and recurse into plain objects and arrays.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.