Created
May 20, 2021 08:31
-
-
Save buhichan/e22b3ecfa21b93eedaa799b6f5174074 to your computer and use it in GitHub Desktop.
deep clone when there's circlular reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseModel { | |
private deepCloneImpl(oldObject: object, intrinsicTypes: string[], clonedMap: WeakMap<object, unknown>){ | |
if (!oldObject || typeof oldObject !== "object") return oldObject; | |
if(clonedMap.has(oldObject)){ | |
return clonedMap.get(oldObject) | |
} | |
if (Array.isArray(oldObject)) { | |
const newObject: any = []; | |
clonedMap.set(oldObject, newObject) | |
for (let i = 0, l = oldObject.length; i < l; ++i){ | |
newObject.push(this.deepCloneImpl(oldObject[i], intrinsicTypes, clonedMap)); | |
} | |
return newObject; | |
} | |
if (0 <= intrinsicTypes.indexOf(oldObject.constructor.name)) { | |
return oldObject; | |
} | |
const newObject = new Object(); | |
clonedMap.set(oldObject, newObject) | |
for (const key in oldObject) { | |
if (key in oldObject) { | |
newObject[key] = this.deepCloneImpl(oldObject[key], intrinsicTypes, clonedMap); | |
} | |
} | |
return newObject; | |
} | |
/** | |
* Deep clone | |
* | |
* @param oldObject | |
* @param intrinsicTypes | |
*/ | |
deepClone(oldObject: object, intrinsicTypes: string[] | null = null) { | |
if (null === intrinsicTypes) { | |
if (!("intrinsicTypes" in this.options)) intrinsicTypes = []; | |
else if (false === this.options.intrinsicTypes) return oldObject; | |
else intrinsicTypes = this.options.intrinsicTypes as string[]; | |
} | |
return this.deepCloneImpl(oldObject, intrinsicTypes, new WeakMap()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment