Object deep clone
by Arjan Haverkamp
JavaScript
// source: https://medium.com/@orami98/11-problems-you-can-solve-natively-in-javascript-no-libraries-required-86d2e51deecc
function deepClone(obj, seen = new WeakMap()) {
// Handle primitives and null
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle circular references
if (seen.has(obj)) {
return seen.get(obj);
}
// Handle Date objects
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle Arrays
if (Array.isArray(obj)) {
const arrCopy = [];
seen.set(obj, arrCopy);
obj.forEach((item, index) => {
arrCopy[index] = deepClone(item, seen);
});
return arrCopy;
}
// Handle RegExp
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags);
}
// Handle Objects
const objCopy = {};
seen.set(obj, objCopy);
Object.keys(obj).forEach(key => {
objCopy[key] = deepClone(obj[key], seen);
});
return objCopy;
}
// Usage example
const original = {
name: 'John',
birthDate: new Date('1990-01-01'),
hobbies: ['reading', 'coding'],
address: {
street: '123 Main St',
city: 'Anytown'
},
greet: function() { return `Hello, I'm ${this.name}`; }
};
const cloned = deepClone(original);
cloned.address.city = 'New City'; // Original remains unchanged
console.log(cloned)