Deep Clone Function
Objective: Implement a function that creates a deep clone of a given object or array, ensuring that all nested structures are also cloned.
Instructions:
- Create a function named
deepClone
that takes an object or array as an argument and returns a deep copy of it.
- The cloned object or array should not share references with the original (i.e., modifying the clone should not affect the original).
- Handle nested objects and arrays, ensuring all levels are cloned.
Example Usage:
const original = { a: 1, b: { c: 2 } };
const cloned = deepClone(original);
cloned.b.c = 3;
console.log(original.b.c); // Output: 2 (original remains unchanged)
console.log(cloned.b.c); // Output: 3 (cloned object is independent)
Requirements:
- The
deepClone
function should work recursively to clone deeply nested objects
and arrays
.
- The function should handle primitive values,
arrays
, and objects
(not Dates
or RegExp
)
Hints:
- Use recursion to iterate through the structure of the object or array.
- Ensure that each nested object or array is cloned and not simply referenced.