Deep clone a nested structure
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
Dateinto a newDatewith 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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.