FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Hard

Deep Clone II

45mins

Implement a function deepClone(value) that performs a deep copy of any JavaScript value, including objects and arrays. The function should also handle circular references to avoid infinite loops.

The function should:

  • Copy all nested objects and arrays.
  • Maintain circular references (i.e., if an object references itself, the cloned object should also reference itself in the same structure).
  • Copy primitive values as-is.

Examples

const obj = { a: 1, b: { c: 2 } }; const clone = deepClone(obj); clone.b.c = 3; console.log(obj.b.c); // 2 const circular = { }; circular.self = circular; const cloneCircular = deepClone(circular); console.log(cloneCircular.self === cloneCircular); // true

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests