Skip to curriculum
Jump to the editor

21.4. Deep clone with cycles, Dates, Maps and Sets

Medium
Topics
25–40 min

Copying 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

JAVASCRIPT
function deepClone(value) // returns the copy
  • value: any value. It is never changed.
  • Returns a copy that shares no object with value, except functions.

Requirements

  1. A value that is not an object (numbers, strings, booleans, null, undefined, BigInts, symbols) and a function are returned as they are.
  2. Plain objects are copied at every depth: changing the copy never changes the original.
  3. Arrays stay arrays, with the same length and the same holes.
  4. A Date is copied to a new Date with the same time.
  5. A RegExp is copied with the same source, flags and lastIndex.
  6. A Map is copied to a new Map; its keys and values are cloned. A Set is copied to a new Set; its members are cloned.
  7. An object that contains itself, directly or several levels down, or through a Map or Set, gives a copy that contains the copy in the same place.
  8. 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.
  9. The copy has the same prototype as the original: class instances keep their class, subclasses of Array, Date, RegExp, Map and Set keep theirs (the copy is still a real array, Date, and so on), and Object.create(null) objects keep a null prototype.
  10. Own enumerable properties are copied, with string and symbol keys, on every kind of object (an extra field on a RegExp, Date, Map or Set too). Non-enumerable properties are not copied.
  11. An own property named __proto__ (as JSON.parse creates) is copied as an ordinary property; it never changes the copy's prototype.
  12. The input is not changed: no marker properties are added.
  13. structuredClone is not used.

Examples

JAVASCRIPT
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;  // false
JAVASCRIPT
const node = { id: 1 };
node.self = node;
const copy = deepClone(node);
copy.self === copy;  // true
copy.self === node;  // false
JAVASCRIPT
const shared = { n: 1 };
const copy = deepClone({ a: shared, b: [shared] });
copy.a === copy.b[0];  // true
copy.a === shared;     // false

Environment

  • Plain JavaScript in a browser page; the tests call the global deepClone from deep-clone.js.
  • structuredClone is 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

  1. 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?
  2. Object.keys does not list symbol keys. Which built-in does?
  3. What does copy["__proto__"] = value do 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
Back to the question
Loading the editor…