30Implement deep clone with circular references, Map, Set, and Date
mediumAbout 35 minutesCodingrecursionobjectsweakmap
Problem
Implement deepClone(value). It returns a copy where every nested object is new, so changing the copy never changes the original.
const original = { tags: new Set(["a"]), meta: new Map([["created", new Date(0)]]) };
original.self = original;
const copy = deepClone(original);
copy.self === copy; // true: the cycle is preserved inside the copy
copy.meta.get("created") === original.meta.get("created"); // false: new DateRequirements
- Clone plain objects and arrays deeply.
- Clone
Date,RegExp,Map(keys and values) andSet. - Handle circular references, and keep shared references shared: if the original uses one object twice, the copy uses one cloned object twice.
- Keep the prototype, so a class instance stays an instance of its class.
- Copy own enumerable symbol keys too.
- Return primitives and functions as they are.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
Anything that is not a non-null object is either immutable (numbers, strings) or not cloneable in a meaningful way (functions). Return it as is.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 5 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.