In JavaScript, data types include string, number, boolean, object, null, and undefined. The concepts of shallow and deep copy specifically apply to objects, as the other types don't require such differentiation.
An object can be visualized as a tree structure where leaf nodes represent primitive types (string, number, boolean, null, undefined) and internal nodes are objects. Copying involves creating a replica of this tree. Deep copying traverses all the way to leaf nodes, while shallow copying stops at certain internal nodes. Additionally, deep copying creates new objects for internal nodes rather then reusing references.
Testing Functions
function verifyShallowCopy(copyFunc) {
const original = { a: 1, b: { c: 2 } };
const copied = copyFunc(original);
return original.b === copied.b;
}
function verifyDeepCopy(copyFunc) {
const original = { a: 1, b: { c: 2 } };
const copied = copyFunc(original);
return original.b !== copied.b && JSON.stringify(original) === JSON.stringify(copied);
}
Shallow Copy Techniques
- Direct assignment:
const shallowCopy1 = obj => obj;
- Manual iteration:
const shallowCopy2 = obj => {
const result = {};
for (const key in obj) {
result[key] = obj[key];
}
return result;
};
- Using Object.assign():
const shallowCopy3 = obj => Object.assign({}, obj);
Deep Copy Methods
- Recursive approach:
function deepCopy1(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
const result = Array.isArray(obj) ? [] : {};
for (const key in obj) {
result[key] = deepCopy1(obj[key]);
}
return result;
}
- JSON serialization:
const deepCopy2 = obj => JSON.parse(JSON.stringify(obj));
- Using Object.create():
const deepCopy3 = obj => Object.create(Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj));
Array Copying
The same principles apply to arrays. For shallow copying, methods like slice() or spread operator can be used:
const arr = [1, [2, 3]];
const shallowArrCopy = arr.slice();
For deep copying arrays, the JSON method works similarly to objects. Note that some shallow copy methods may appear to perform deep copying when dealing with fllat structures (no nested objects or arrays). However, for comprehensive deep copying, all nested structures must be properly handled.