1
0
Fork 0
forked from svrjs/svrjs

Optimize deepClone function

This commit is contained in:
Dorian Niemiec 2024-08-28 07:14:13 +02:00
parent fb887e4122
commit 4b37e08bb5

View file

@ -4,41 +4,46 @@ function deepClone(obj) {
return obj; return obj;
} }
const recurse = (obj, _objectsArray, _clonesArray) => { const objectsArray = [];
if (!_objectsArray) _objectsArray = []; const clonesArray = [];
if (!_clonesArray) _clonesArray = [];
let objectsArrayIndex = _objectsArray.indexOf(obj); const recurse = (obj) => {
if (objectsArrayIndex != -1) { let objectsArrayIndex = -1;
return _clonesArray[objectsArrayIndex];
for (let i = 0; i < objectsArray.length; i++) {
if (objectsArray[i] == obj) {
objectsArrayIndex = i;
break;
}
} }
let clone; if (objectsArrayIndex != -1) {
return clonesArray[objectsArrayIndex];
}
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
clone = []; const clone = [];
_objectsArray.push(obj); objectsArray.push(obj);
_clonesArray.push(clone); clonesArray.push(clone);
obj.forEach((item, index) => { obj.forEach((item, index) => {
clone[index] = clone[index] =
typeof item !== "object" || item === null typeof item !== "object" || item === null ? item : recurse(item);
? item
: recurse(item, _objectsArray, _clonesArray);
}); });
return clone;
} else { } else {
clone = {}; const clone = {};
_objectsArray.push(obj); objectsArray.push(obj);
_clonesArray.push(clone); clonesArray.push(clone);
Object.keys(obj).forEach((key) => { Object.keys(obj).forEach((key) => {
clone[key] = clone[key] =
typeof obj[key] !== "object" || obj[key] === null typeof obj[key] !== "object" || obj[key] === null
? obj[key] ? obj[key]
: recurse(obj[key], _objectsArray, _clonesArray); : recurse(obj[key]);
}); });
return clone;
} }
return clone;
}; };
return recurse(obj); return recurse(obj, objectsArray, clonesArray);
} }
module.exports = deepClone; module.exports = deepClone;