AniUI Academy

Deep clone a nested structure

hardArrays & ObjectsHigh freq+350 XPPractice

The spread operator copies one level. Edit copy.address.city and you have just edited the original too, which is how undo stacks and form drafts quietly corrupt state. JSON.parse(JSON.stringify(x)) is the usual escape hatch, and it throws on circular references and destroys Dates.

Implement deepClone(value). Return a copy where every nested plain object and array is a new object, so no part of the result is shared with the input. Primitives are returned as they are. A Date is cloned into a new Date with the same time value. Arrays clone into arrays and objects into objects. Two important reference rules: if the same object appears at two places in the input, it must appear as one shared object at both places in the output; and a structure that refers to itself must clone without infinite recursion, with the clone referring to itself in the same way. Assume the input contains only primitives, plain objects, arrays and Dates.

What it has to do

  • Recursively copy plain objects and arrays so nothing is shared with the input.
  • Return primitives unchanged.
  • Clone a Date into a new Date with the same time value.
  • Preserve sharing: one object appearing twice in the input appears as one object twice in the output.
  • Handle circular references without infinite recursion.

Where it's been asked

  • Meta
  • Microsoft
  • Atlassian

From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

Need a nudge?

Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.