Skip to the solution
HardDSA10 min read

Implement deepClone — handle Dates, RegExp, Map, Set & circular refs

969 views

The problem

Problem, as an interviewer would state it: "Write deepClone(obj) that correctly clones plain objects, arrays, Dates, RegExps, Maps and Sets, and handles circular references. Discuss edge cases, runtime, and alternatives."

Examples:

Code
const a = { d: new Date(0), m: new Map([["k", { deep: 1 }]]), list: [1, [2]] };
a.self = a;
const b = deepClone(a);
b.self === b;     // true  (the cycle points at the copy, not the original)
b.m !== a.m;      // true  (nothing is shared with the original)

Clarifying questions expected:

  • Should class instances keep their prototype, and are functions copied or shared?
  • Are Map keys cloned as well as values, and what about symbol keys and non-enumerable properties?
  • Why not structuredClone, and which kinds (Errors, typed arrays) are out of scope?

Code / implementation expected: Yes — real code, checked against structuredClone and on circular and shared structures.

  • deep-clone
  • structuredClone
  • circular

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: deepClone reproduces the exact graph shape (cycles and sharing) on random graphs, keeps what structuredClone drops, and reproduces each classic bug

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 143 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Rotate array N times

Continue