deep clone
by harsh dand
JavaScript
function deepClone(obj) {
// handling primitive types
if (typeof obj !== 'object' || obj === null) {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof Set) {
const copy = new Set();
for(let i of obj){
copy.add(i);
}
return copy;
}
if (Array.isArray(obj)) {
return obj.map((item) => deepClone(item));
}
if (obj instanceof Object) {
let copy = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepClone(obj[key]);
}
}
return copy;
}
}
const obj = {
a: new Date(),
b: [{
c: {
d: '1'
}
}],
c: {
d: 2
},
e: null,
f: undefined,
g: new Set([{a:'1'}])
};
console.log(new Set([{a:'1'}]).values())