I recently wrote this function for deep cloning an object in javascript, but with the given time complexity it would be extremely slow, any tips on making it more effecient?
function deepClone(obj){
let clone = {};
for (let k in obj){
let v = obj[k];
if (!array.isArray(v)&&("object"!==typeof v)){
clone[k]=v;
continue;
} else {
if (typeof v==="object"){
let RCRSD = deepClone(v);
clone[k]=RCRSD;
} else {
if (array.isArray(v)){
let arr=[];
for (let e of v){
if (typeof e==="object"){
arr.push(deepClone(e));
} else {
arr.push(e)
};
clone[k]=arr;
};
};
};
};
};
};
This method also does not account for other data structures which is another problem
2
Answers
You can use recursion and check the value of the key
This isn’t necessarily more efficient (your code seems to be about there sans the weird conditionals), but it does address some bugs in your code (incorrectly handling arrays), and just a bit cleaner.