21.4. Deep clone with cycles, Dates, Maps and Sets
Topics
This question is in
21. Recursion and nested dataCopying with { ...state } or Object.assign copies one level: the inner objects are still shared, so changing the copy's user.address changes the original. An undo history, a form with a "reset" button, or a test fixture that must not leak between tests all need a deep copy, where nothing reachable from the copy is shared with the original.
Write deepClone(value) in deep-clone.js. It copies plain objects, arrays, class instances, Date, RegExp, Map and Set at every depth. The hard parts are the graph shapes: an object that points to itself must become a copy that points to itself, and an object used in two places must become one copy used in two places.
Signature
function deepClone(value) // returns the copyvalue: any value. It is never changed.- Returns a copy that shares no object with
value, except functions.
Requirements
- A value that is not an object (numbers, strings, booleans,
null,undefined, BigInts, symbols) and a function are returned as they are. - Plain objects are copied at every depth: changing the copy never changes the original.
- Arrays stay arrays, with the same
lengthand the same holes. - A
Dateis copied to a newDatewith the same time. - A
RegExpis copied with the samesource,flagsandlastIndex. - A
Mapis copied to a newMap; its keys and values are cloned. ASetis copied to a newSet; its members are cloned. - An object that contains itself, directly or several levels down, or through a
MaporSet, gives a copy that contains the copy in the same place. - An object reachable along several paths is copied once, and every path in the copy leads to that one copy, across objects, arrays, Maps and Sets.
- The copy has the same prototype as the original: class instances keep their class, subclasses of
Array,Date,RegExp,MapandSetkeep theirs (the copy is still a real array, Date, and so on), andObject.create(null)objects keep anullprototype. - Own enumerable properties are copied, with string and symbol keys, on every kind of object (an extra field on a
RegExp,Date,MaporSettoo). Non-enumerable properties are not copied. - An own property named
__proto__(asJSON.parsecreates) is copied as an ordinary property; it never changes the copy's prototype. - The input is not changed: no marker properties are added.
structuredCloneis not used.
Examples
const original = { user: { name: "Ada" }, since: new Date(0), tags: new Set(["a"]) };
const copy = deepClone(original);
copy.user.name = "Grace";
original.user.name; // "Ada"
copy.since instanceof Date; // true
copy.tags === original.tags; // falseconst node = { id: 1 };
node.self = node;
const copy = deepClone(node);
copy.self === copy; // true
copy.self === node; // falseconst shared = { n: 1 };
const copy = deepClone({ a: shared, b: [shared] });
copy.a === copy.b[0]; // true
copy.a === shared; // falseEnvironment
- Plain JavaScript in a browser page; the tests call the global
deepClonefromdeep-clone.js. structuredCloneis removed during one test.- Out of scope: typed arrays,
ArrayBuffer,WeakMap,WeakSet, boxed primitives (new Number(1)), DOM nodes, getters and setters (a getter's current value is copied).
Hints
- To give a cycle in the original a cycle in the copy, the copy of an object has to exist before its properties are copied. Where do you record it?
Object.keysdoes not list symbol keys. Which built-in does?- What does
copy["__proto__"] = valuedo on an ordinary object?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it