Implement cloneDeep
Write cloneDeep(value): a copy that shares no mutable state with the original. A spread like { ...obj } copies one level; this copy goes all the way down.
Rules
- Primitives and functions come back as they are.
- Arrays stay arrays, and plain objects are copied property by property, including symbol keys.
- A
Datebecomes a newDatewith the same time. ARegExpbecomes a newRegExpwith the same source and flags. - A
MaporSetbecomes a new one of the same kind, with its keys and values deep-cloned. - The copy keeps the original's prototype, so a class instance is still an instance of its class. A null-prototype object stays one.
- Cycles and shared references survive. An object that refers to itself yields a clone that refers to itself. Two properties pointing at one object point at one copy.
structuredClone is switched off while your code runs. It would also fail two of the rules above.
Hints
Hint 1
Keep a WeakMap from each original object to its copy. Check it first, and register the new copy before recursing into the object's children, or a cycle recurses forever.
Hint 2
Handle the special types before the generic case: Date, RegExp, Map, Set. For everything else, Object.create(Object.getPrototypeOf(value)) keeps the prototype, or use [] for arrays.
Hint 3
Reflect.ownKeys returns string and symbol keys alike, so a single loop copies both.