Implement deepClone(value). It returns a copy of value that shares no objects with the original, so changing the copy never changes the original.
What to copy:
- Primitives (numbers, strings, booleans,
null,undefined, symbols, bigints) are returned as they are. So are functions. - Plain objects become new objects with the same own keys (from
Object.keys) and cloned values. - Arrays become new arrays with cloned items.
- Dates become new
Dateobjects with the same time. - Maps become new maps, and Sets become new sets. Both their keys and their values are cloned, and insertion order is kept.
References inside the value:
- If the same object appears in two places in the original, it is copied once, and both places in the copy point to that one copy.
- The value may contain cycles, such as
obj.self = obj. In the copy,copy.selfmust becopy.
Don't use structuredClone or JSON methods.
Input: const a = { n: [1, 2], d: new Date(0) }; const b = deepClone(a); b.n.push(3);
Output: a.n is still [1, 2]; b.d is a new Date with the same time
Input: const o = { name: 'loop' }; o.self = o; const c = deepClone(o);
Output: c.self === c, and c !== o