javascriptadvanced15 minutes

Fix the Memory Leak and Logic Bug in a Recursive Deep Clone Function

This challenge provides a broken implementation of a deep clone function in JavaScript. The function is supposed to recursively clone any object or array, preserving nested structures without reference sharing. However, the current implementation has both a logic bug causing incorrect cloning of nested structures and a memory leak due to undetected circular references. Your task is to fix these issues and optimize the function for deep cloning complex objects.

Challenge prompt

You're given a deepClone function intended to recursively clone objects and arrays. However, it fails for complex nested objects, especially those containing circular references. It reuses references incorrectly, can cause infinite recursion, and leaks memory. Fix the deepClone function to correctly and safely deep clone any input (object or array), handle circular references gracefully, and ensure no memory leaks occur.

Guidance

  • Detect and keep track of already cloned objects to resolve circular references.
  • Ensure arrays and objects are cloned properly without referencing the original.
  • Avoid global variables or growing state that causes memory leaks.
  • Use a helper parameter (like a WeakMap) to store references during recursion.

Hints

  • Use a WeakMap to map original objects to their clones during recursion to avoid infinite loops.
  • Return primitive types immediately without cloning, since they are immutable.
  • Avoid recreating large objects repeatedly without garbage collection support.

Starter code

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    let cloneArr = [];
    for (let i = 0; i < obj.length; i++) {
      cloneArr[i] = deepClone(obj[i]);
    }
    return cloneArr;
  } else {
    let cloneObj = {};
    for (let key in obj) {
      cloneObj[key] = deepClone(obj[key]);
    }
    return cloneObj;
  }
}

Expected output

const circularObj = {}; circularObj.self = circularObj; const cloned = deepClone(circularObj); console.log(cloned !== circularObj); // true console.log(cloned.self === cloned); // true const original = { a: 1, b: { c: 2 } }; const copy = deepClone(original); console.log(copy !== original); // true console.log(copy.b !== original.b); // true console.log(copy.b.c === 2); // true

Core concepts

recursiondeep cloningmemory managementcircular referencesWeakMap

Challenge a Friend

Send this duel to someone else and see if they can solve it.