FrontendInterviews.dev

Loading problem…

45. Deep Clone with Circular References

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

This problem builds on deep-clone. Complete that first, then load your solution to continue.

Implement deepClone with support for circular references, Map, Set, Date, and RegExp.

Requirements

1) Supported values

  • Primitives, arrays, and plain objects
  • Map (clone keys and values)
  • Set (clone values)
  • Date
  • RegExp

2) Circular references

  • Prevent infinite recursion.
  • Preserve graph shape (self-reference in source should map to self-reference in clone).
  • Use a visited structure (typically WeakMap).

3) Independence

  • Mutating cloned nested values must not mutate originals.

4) Scope note

  • Function cloning and symbol-key-specific behavior are out of scope for this level.

Examples

const obj = { name: "A" }
obj.self = obj
const cloned = deepClone(obj)

cloned !== obj              // true
cloned.self === cloned      // true
const map = new Map([["k", { n: 1 }]])
const cloned = deepClone(map)
cloned.get("k").n = 2

map.get("k").n // 1

Constraints

  • Handle circular references without infinite recursion.
  • Clone Map keys and values recursively.
  • Clone Set values recursively.
  • Clone Date and RegExp objects correctly.
  • Preserve structural independence between original and clone.