Implement deepClone
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement deepClone(value). It returns a deep copy of value: every nested object and array is copied too, so changing the copy never changes the original.
A spread ({ ...object }) or Object.assign only copies the top level, and nested objects stay shared between the original and the "copy".
const original = { user: { name: 'Dana' }, tags: ['a', 'b'] }
const copy = deepClone(original)
copy.user.name = 'Noa'
copy.tags.push('c')
original.user.name // 'Dana'
original.tags // ['a', 'b']Requirements
- Primitives (
string,number,boolean,null,undefined,bigint,symbol) are returned as they are. - Plain objects and arrays are copied, at every level.
Dateobjects are copied as newDates with the same time.- Circular references are kept: if an object refers to itself (directly or through other objects), the copy refers to the copy, and cloning does not loop forever.
- Functions are not copied: the copy holds the same function.
Note
Don't use structuredClone or JSON.parse(JSON.stringify(...)). The second one also gets Dates, undefined and circular references wrong.
Approach
Recurse through the value, with a Map from each original object to its copy:
- Primitives and functions: if
valueis not an object, or isnull, return it as it is.typeofa function is'function', so functions take this path too. - Already copied: if the
Maphasvalue, return the copy stored there. This is what handles circular references. Date: returnnew Date(value.getTime()).- Arrays and objects: create an empty array or object, store it in the
Mapfirst, then fill it by cloning each value under each key.
Why register the copy before filling it
With const a = {}; a.self = a, cloning a creates the copy, then clones a.self, which is a again. If the copy is already in the Map, that inner call returns it and the copy's self points at the copy. If you register it only after the loop, the inner call starts cloning a again, and again, until the stack overflows.
The same Map also keeps shared references shared: if two keys point at one object, the copy has two keys pointing at one copied object.
Complexity
O(n) time and space, where n is the number of values reachable from the input. Each object is copied once thanks to the Map.
Follow-ups interviewers ask
- More types:
MapandSet(clone their entries),RegExp, typed arrays, and class instances (keep the prototype withObject.create(Object.getPrototypeOf(value))). - Symbol keys and non-enumerable properties:
Object.keysskips them.Reflect.ownKeysand property descriptors copy them. - Deep recursion: a very long linked list overflows the stack. An explicit stack of
[original, copy]pairs avoids that. structuredClone: the built-in in browsers and Node. It handles cycles,Map,SetandDate, but throws on functions and DOM nodes.
Reference solution
/**
* @template T
* @param {T} value
* @returns {T}
*/
export default function deepClone(value) {
return cloneWith(value, new Map())
}
function cloneWith(value, seen) {
if (typeof value !== 'object' || value === null) return value
if (seen.has(value)) return seen.get(value)
if (value instanceof Date) return new Date(value.getTime())
const copy = Array.isArray(value) ? [] : {}
seen.set(value, copy)
for (const key of Object.keys(value)) {
copy[key] = cloneWith(value[key], seen)
}
return copy
}export default function deepClone<T>(value: T): T {
return cloneWith(value, new Map()) as T
}
function cloneWith(value: unknown, seen: Map<object, unknown>): unknown {
if (typeof value !== 'object' || value === null) return value
if (seen.has(value)) return seen.get(value)
if (value instanceof Date) return new Date(value.getTime())
const copy: Record<string, unknown> = Array.isArray(value) ? [] : {}
seen.set(value, copy)
for (const key of Object.keys(value)) {
copy[key] = cloneWith((value as Record<string, unknown>)[key], seen)
}
return copy
}