1
0
Fork 0
forked from svrjs/svrjs
This repository has been archived on 2024-11-10. You can view files and clone it, but cannot push or open issues or pull requests.
svrjs/src/utils/deepClone.js

50 lines
1.1 KiB
JavaScript
Raw Normal View History

// Function to deep clone an object or array
function deepClone(obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
2024-08-28 07:14:13 +02:00
const objectsArray = [];
const clonesArray = [];
2024-08-28 07:14:13 +02:00
const recurse = (obj) => {
let objectsArrayIndex = -1;
for (let i = 0; i < objectsArray.length; i++) {
if (objectsArray[i] == obj) {
objectsArrayIndex = i;
break;
}
}
2024-08-28 07:14:13 +02:00
if (objectsArrayIndex != -1) {
return clonesArray[objectsArrayIndex];
}
if (Array.isArray(obj)) {
2024-08-28 07:14:13 +02:00
const clone = [];
objectsArray.push(obj);
clonesArray.push(clone);
obj.forEach((item, index) => {
2024-08-27 22:52:36 +02:00
clone[index] =
2024-08-28 07:14:13 +02:00
typeof item !== "object" || item === null ? item : recurse(item);
});
2024-08-28 07:14:13 +02:00
return clone;
} else {
2024-08-28 07:14:13 +02:00
const clone = {};
objectsArray.push(obj);
clonesArray.push(clone);
Object.keys(obj).forEach((key) => {
2024-08-27 22:51:41 +02:00
clone[key] =
typeof obj[key] !== "object" || obj[key] === null
? obj[key]
2024-08-28 07:14:13 +02:00
: recurse(obj[key]);
});
2024-08-28 07:14:13 +02:00
return clone;
}
};
2024-08-28 07:14:13 +02:00
return recurse(obj, objectsArray, clonesArray);
}
module.exports = deepClone;