forked from svrjs/svrjs
Optimize deepClone function
This commit is contained in:
parent
fb887e4122
commit
4b37e08bb5
1 changed files with 24 additions and 19 deletions
|
@ -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;
|
||||||
|
|
Reference in a new issue