Recursively copy objects so nested changes stay isolated
Implement a function deepClone that takes an object as input and returns a deep copy of it. Unlike a shallow copy, which only copies the outermost layer, a deep copy replicates every level of nested objects. This means that changes made to the nested objects in the cloned object do not affect the original object. Modern browsers also ship structuredClone(), but this problem asks you to write a deep clone yourself.
This function is crucial in scenarios where you need to manipulate data while preserving the original structure for future use. Deep cloning is a common requirement in frontend development, especially in state management, where immutability is a key concept.
Consider the following object as an example:
const source = {
a: 10,
b: 20,
c: {
d: 30,
e: ['a', 'b', 1],
f: {
g: 1
}
}
}
Your task is to create a deepClone function that accurately duplicates this structure, including all nested objects and arrays. Changes to any level of the cloned object should not impact the original object.
Here’s a basic usage example where changes to the cloned object do not affect the original:
const obj = { role: 'foo' };
const clonedObj = deepClone(obj);
clonedObj.role = 'bar';
console.log(obj.role); // Output: 'foo'
console.log(clonedObj.role); // Output: 'bar'
The challenge involves understanding and applying recursion for objects within objects, ensuring each level is appropriately cloned.
This problem tests your ability to work with references in JavaScript, a fundamental concept in ensuring data integrity and preventing unintended side effects in your applications.