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

49 lines
1.2 KiB
JavaScript

// Function to deep clone an object or array
function deepClone(obj, isFullObject) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
const objectsArray = [];
const clonesArray = [];
const recurse = (obj) => {
let objectsArrayIndex = -1;
for (let i = 0; i < objectsArray.length; i++) {
if (objectsArray[i] == obj) {
objectsArrayIndex = i;
break;
}
}
if (objectsArrayIndex != -1) {
return clonesArray[objectsArrayIndex];
}
if (Array.isArray(obj)) {
const clone = [];
objectsArray.push(obj);
clonesArray.push(clone);
obj.forEach((item, index) => {
clone[index] =
typeof item !== "object" || item === null ? item : recurse(item);
});
return clone;
} else {
const clone = isFullObject ? {} : Object.create(null);
objectsArray.push(obj);
clonesArray.push(clone);
Object.keys(obj).forEach((key) => {
clone[key] =
typeof obj[key] !== "object" || obj[key] === null
? obj[key]
: recurse(obj[key]);
});
return clone;
}
};
return recurse(obj, objectsArray, clonesArray);
}
module.exports = deepClone;