Skip to main content
09

Implement deepClone

MediumrecursionobjectsMap

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".

js
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.
  • Date objects are copied as new Dates 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:

  1. Primitives and functions: if value is not an object, or is null, return it as it is. typeof a function is 'function', so functions take this path too.
  2. Already copied: if the Map has value, return the copy stored there. This is what handles circular references.
  3. Date: return new Date(value.getTime()).
  4. Arrays and objects: create an empty array or object, store it in the Map first, 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.

Loading diagram...

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: Map and Set (clone their entries), RegExp, typed arrays, and class instances (keep the prototype with Object.create(Object.getPrototypeOf(value))).
  • Symbol keys and non-enumerable properties: Object.keys skips them. Reflect.ownKeys and 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, Set and Date, but throws on functions and DOM nodes.

Reference solution

js
/**
 * @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
}
ts
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
}