Problem 40

Clone Recursion Challenge

Given an object or array, return a deep clone where every nested object and array is a new reference. Primitive values should be copied as-is.

Function Signature

clone(input)

Parameters

  • input — an object or array, potentially containing nested objects and arrays.

Output

Return a new object or array that deeply equals the input but shares no references with it.

Constraints

  • The function must use recursion.
  • Do not use JSON.parse, JSON.stringify, or Object.assign.
  • The input must not be mutated.
  • The function should accept exactly one argument.

Examples

clone({a: 1, b: {bb: {bbb: 2}}, c: 3})
→ {a: 1, b: {bb: {bbb: 2}}, c: 3}  (new references for all nested objects)

clone([1, [2, []], 3, [[[4]], 5]])
→ [1, [2, []], 3, [[[4]], 5]]  (new references for all nested arrays)