← JavaScript Coding

Deep Clone II

hardobjectsrecursioncycles
Asked at
Adobe
Amazon
Google
Microsoft
Salesforce
Adobe, Amazon, Google, Microsoft, Salesforce

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, and Set.
  • 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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

4. Improve a function

JS CodingMedium

Camel Case Keys

JS CodingMedium

Get and Set by Path

JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Adobe interview
  • Amazon interview
  • Google interview
  • Microsoft interview
  • Salesforce interview