FrontendInterviews.dev

Loading problem…

48. Complete Deep Clone

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

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

Implement a configurable deepClone that extends level-II cloning with symbol keys, function policy, weak-collection policy, and custom handlers.

Signature

deepClone(value, options?)

Options

  • cloneFunctions (boolean, default false)
  • false: keep original function reference.
  • true: return a callable wrapper function.
  • customHandlers (object, default {})
  • Keyed by constructor name (e.g. Date, URL).
  • Handler signature: (value, clone) => any.
  • weakCollections ("empty" | "reference", default "empty")
  • "empty": clone WeakMap/WeakSet as new empty instances.
  • "reference": reuse original WeakMap/WeakSet references.

Requirements

1) Base support (from previous level)

  • Primitives, arrays, plain objects, cycles
  • Map, Set, Date, RegExp

2) Additional behavior

  • Preserve enumerable symbol-keyed properties on objects.
  • Apply function policy from cloneFunctions.
  • Apply weak collection policy from weakCollections.
  • If a matching custom handler exists, use it for that type.

3) Graph invariants

  • Preserve circular graph shape for supported object types.
  • Mutating clone should not mutate original for deeply cloned paths.

Examples

const sym = Symbol("k")
const original = { [sym]: { n: 1 } }
const cloned = deepClone(original)
cloned[sym].n = 9
// original[sym].n is still 1
const out = deepClone({ when: new Date("2023-01-01") }, {
  customHandlers: {
    Date: (d) => `DATE:${d.toISOString()}`
  }
})
// out.when is "DATE:2023-01-01T00:00:00.000Z"

Constraints

  • Preserve cycle safety for supported object graph branches.
  • Preserve enumerable symbol-keyed properties on cloned objects.
  • Respect cloneFunctions and weakCollections policy options.
  • Invoke matching customHandlers by constructor name before default type logic.
  • Maintain deep independence for branches that are cloned (not referenced by policy).