Build a Memoized Deep Clone Function with Circular Reference Handling
Create an advanced JavaScript function that performs a deep clone of any given object, including nested objects and arrays, while efficiently handling circular references using memoization to avoid infinite loops.
Challenge prompt
Write a JavaScript function named deepClone that takes an object or array of any depth, and returns a fully deep cloned copy of it. Your function must handle circular references gracefully by reusing previously cloned instances to prevent infinite recursion or stack overflow errors. The function should also correctly clone built-in JavaScript types such as Date and RegExp objects. Note that functions and DOM elements do not need to be cloned and may be left as-is in the output. Example usage: const original = { a: 1 }; original.self = original; const cloned = deepClone(original); console.log(cloned !== original); // true console.log(cloned.self === cloned); // true Your deepClone function should support cloning deeply nested structures and circular references without performance degradation caused by redundant cloning operations.
Guidance
- • Use a WeakMap or Map to keep track of objects that have already been cloned and their copies to manage circular references.
- • Implement recursive cloning and explicitly check object types such as Date and RegExp to clone them correctly.
- • Avoid cloning functions or DOM elements; simply copy their references as-is.
Hints
- • Start by checking if the input is a primitive, return it directly if so.
- • Store each original object as a key in a Map associated with its cloned counterpart to reuse clones for circular references.
- • For arrays and general objects, iterate over their properties or indices recursively applying deepClone.
Starter code
function deepClone(obj, map = new Map()) {
// Your implementation here
}Expected output
const original = { a: 1 }; original.self = original; const cloned = deepClone(original); console.log(cloned !== original); // true console.log(cloned.self === cloned); // true const regex = /test/g; const obj = { d: new Date(), r: regex }; const clonedObj = deepClone(obj); console.log(clonedObj.d instanceof Date); // true console.log(clonedObj.r instanceof RegExp); // true
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.