Deep clone an object graph preserving cycles and shared refs
A diagram editor keeps its document as an object graph: shapes point at the layers they belong to, layers point back at their shapes, connectors point at two shapes, and a Map indexes shapes by id. Before every edit the editor snapshots the document for undo. A naive deep copy breaks here: it loops forever on cycles, and it turns one shared shape into two different copies. Implement cloneGraph(value), a deep copy that keeps the shape of the graph.
cloneGraph(value) // => deep copy of value
null and undefined) and functions are returned as is.instanceof and methods keep working. Copy every own enumerable property, including symbol keys, cloning each value. Skip non-enumerable properties.Date: a new Date with the same time. RegExp: a new regex with the same source, flags, and lastIndex.Map and Set: a new Map / Set with the same insertion order. Keys and values are cloned too, so an object used as a key is replaced by its clone.structuredClone or JSON. Do not mutate the input.class Shape {
constructor(id) { this.id = id; }
label() { return `shape ${this.id}`; }
}
const layer = { name: 'Background', shapes: [] };
const a = new Shape('a');
const b = new Shape('b');
a.layer = layer;
b.layer = layer;
layer.shapes.push(a, b);
const doc = {
layers: [layer],
connector: { from: a, to: b },
index: new Map([['a', a], ['b', b]]),
savedAt: new Date('2026-03-01T10:00:00Z'),
};
const copy = cloneGraph(doc);
copy.layers[0].shapes[0] === copy.connector.from; // => true (shared)
copy.index.get('b') === copy.layers[0].shapes[1]; // => true
copy.layers[0].shapes[0].layer === copy.layers[0]; // => true (cycle)
copy.connector.from === a; // => false (a new object)
copy.connector.from instanceof Shape; // => true
copy.connector.from.label(); // => 'shape a'
copy.savedAt.getTime() === doc.savedAt.getTime(); // => true
const self = { name: 'loop' };
self.self = self;
const selfCopy = cloneGraph(self);
selfCopy.self === selfCopy; // => true
Error, WeakMap, DOM nodes) are not tested.