coding round · ~25 min
JavaScriptintermediate

Implement deepClone

Write deepClone(value) that returns a deep copy of value, so changing the copy never affects the original. It should handle:

  • primitives such as 42, 'text', null and undefined, which are returned as they are
  • plain objects and arrays, nested to any depth
  • Date, Map and Set (the values inside a Map or Set are cloned deeply too)
  • circular references: if obj.self === obj, then copy.self === copy

If the same object appears in several places, the copy should reuse a single clone of it, mirroring the original structure.

  • deepClone({ a: [1, { b: 2 }] }) → an equal object whose array and inner object are new
  • deepClone(new Map([['k', { n: 1 }]])) → a new Map holding a new { n: 1 }
  • deepClone(new Date(0)) → a new Date with the same time

Define deepClone in the editor. 7 tests will call it.

solution.js
function deepClone(value) {
  // Return a deep copy of value.
  // Handle objects, arrays, Date, Map, Set and circular references.
}

Tests⌘/Ctrl + Enter to run

returns primitives as they are
copies nested objects and arrays
changing the copy does not change the original
clones Date objects
clones Maps and Sets deeply
handles circular references
keeps shared references shared
esc