← All tasksJavaScript · Senior
deepClone: deep copy
Write a function deepClone(value) that makes a deep copy of objects, arrays, Date, Map and Set at any depth. Primitives and functions are returned as is.
The copy must survive circular references (obj.self = obj) and preserve shared references: if two fields pointed to one object, in the copy they point to one copy too. Solve it without structuredClone.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (7)
const src = { a: 1, nested: { b: [1, { c: 2 }] } }; const copy = deepClone(src); expect(copy).toEqual(src); expect(copy.nested === src.nested).toBe(false); expect(copy.nested.b[1] === src.nested.b[1]).toBe(false);
const date = new Date('2024-01-02T03:04:05Z'); const copy = deepClone({ date }); expect(copy.date).toBeInstanceOf(Date); expect(copy.date.getTime()).toBe(date.getTime()); expect(copy.date === date).toBe(false);
const src = { m: new Map([['k', { v: 1 }]]), s: new Set([1, 2]) }; const copy = deepClone(src); expect(copy).toEqual(src); expect(copy.m.get('k') === src.m.get('k')).toBe(false); expect(copy.s === src.s).toBe(false);
const src = { name: 'root' }; src.self = src; const copy = deepClone(src); expect(copy.self).toBe(copy); expect(copy === src).toBe(false);
const shared = { x: 1 }; const copy = deepClone({ a: shared, b: shared }); expect(copy.a).toBe(copy.b); expect(copy.a === shared).toBe(false);
expect(deepClone(5)).toBe(5); expect(deepClone(null)).toBe(null); expect(deepClone('x')).toBe('x');
const f = () => 1; expect(deepClone({ f }).f).toBe(f);