JavaScriptFundamental (ES6), part 1
Deep clone with circular references in JavaScript
92 a deep clone that survives a cycle
hardWrite deepClone(value) that copies nested objects, arrays, Date, Map and Set, and does not fall into an endless loop when the data points back at itself. Prove the cycle came out as a cycle, prove two references to one object stay two references to one copy, and show what the clone quietly drops.
Stuck? Three hints, smallest first
- 1. The cycle problem is a memo problem: keep a record of "I have already started copying this object, and here is the copy".
- 2. A
WeakMapfrom original to copy is the record. Put the empty copy in it before you fill it, or the recursion reaches the cycle before the entry exists. - 3. Recursion carries the memo as a default parameter:
(value, seen = new WeakMap()). Fresh at the top call, shared all the way down.
const deepClone = (value, seen = new WeakMap()) => {
if (value === null || typeof value !== 'object') return value; // primitives and functions
if (seen.has(value)) return seen.get(value); // the cycle stops here
if (value instanceof Date) return new Date(value.getTime());
if (value instanceof Map) {
const copy = new Map();
seen.set(value, copy);
for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
return copy;
}
if (value instanceof Set) {
const copy = new Set();
seen.set(value, copy);
for (const v of value) copy.add(deepClone(v, seen));
return copy;
}
const copy = Array.isArray(value) ? [] : {};
seen.set(value, copy); // BEFORE filling it
for (const [k, v] of Object.entries(value)) copy[k] = deepClone(v, seen);
return copy;
};
const REF = Symbol('internal ref');
const vendor = {
name: 'Ngozi Traders',
stock: [{ sku: 'GRP-1', units: 12 }, { sku: 'GRP-2', units: 3 }],
joined: new Date('2023-02-14T00:00:00.000Z'),
tags: new Set(['wholesale', 'verified']),
prices: new Map([['GRP-1', 4500]]),
greet() { return 'Nno'; },
};
vendor[REF] = 'v-01';
const copy = deepClone(vendor);
const unitsBefore = copy.stock[0].units;
copy.stock[0].units = 99;
const unitsInCopy = copy.stock[0].units;
const unitsInOriginal = vendor.stock[0].units;
const branch = { name: 'Onitsha', parent: null };
const chain = { name: 'HQ', branches: [branch] };
branch.parent = chain; // the cycle
const chainCopy = deepClone(chain);
const shared = { vat: 0.075 };
const twice = { retail: shared, wholesale: shared };
const twiceCopy = deepClone(twice);
let jsonError = 'no error';
try { JSON.stringify(chain); } catch (e) { jsonError = e.constructor.name; }
console.log('deep copy :', copy.name, copy.stock, '| original:', vendor.stock[0].units);
console.log('cycle :', chainCopy.branches[0].parent === chainCopy);
console.log('alias :', twiceCopy.retail === twiceCopy.wholesale);
console.log('JSON :', jsonError);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the clone holds the same data in different objects', [copy.name, unitsBefore, copy === vendor, copy.stock === vendor.stock], ['Ngozi Traders', 12, false, false]);
test('so writing deep inside the clone leaves the original alone', [unitsInCopy, unitsInOriginal], [99, 12]);
test('a Date comes back a Date, same instant, new identity', [copy.joined instanceof Date, copy.joined === vendor.joined, copy.joined.toISOString()], [true, false, '2023-02-14T00:00:00.000Z']);
test('Map and Set are rebuilt rather than shared', [[...copy.prices], [...copy.tags], copy.tags === vendor.tags], [[['GRP-1', 4500]], ['wholesale', 'verified'], false]);
test('the cycle is a cycle again, and it points at the copy', [chainCopy.branches[0].parent === chainCopy, chainCopy.branches[0].parent === chain], [true, false]);
test('two references to one object stay two references to one copy', twiceCopy.retail === twiceCopy.wholesale, true);
test('the JSON round trip cannot do that at all', jsonError, 'TypeError');
test('a function is carried across by reference, not copied', [copy.greet === vendor.greet, copy.greet()], [true, 'Nno']);
test('Object.entries never sees symbol keys, so the clone drops them', [Object.getOwnPropertySymbols(vendor).length, Object.getOwnPropertySymbols(copy).length], [1, 0]);
The memo is the whole exercise, and the order of two lines is the whole memo. seen.set(value, copy) has to run before the loop that fills copy, because the recursion can come back around to value while that loop is still running. Set it after and the guard never fires: the function calls itself for ever and the panel dies. A WeakMap rather than a Map so that finishing the clone does not pin the originals in memory.
The same memo gives you something subtler for free. { retail: shared, wholesale: shared } is one object referenced twice, and the clone preserves that: one copy, referenced twice. A naive clone would produce two independent copies, and code that writes through retail expecting wholesale to follow would silently stop working.
What it drops is worth knowing before you rely on it: symbol keys and non-enumerable properties, because Object.entries lists neither; the prototype, because a class instance comes back as a plain object; and getters, which are read once and frozen into plain values. Functions come across by reference, which is usually what you want and is exactly what the built-in structuredClone refuses to do — it handles cycles, Dates, Maps, Sets and typed arrays properly, and throws on a function or a DOM node. Reach for it first; write this when you need the parts it will not take.