Skip to content

Instantly share code, notes, and snippets.

@buhichan
Created May 20, 2021 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buhichan/e22b3ecfa21b93eedaa799b6f5174074 to your computer and use it in GitHub Desktop.
Save buhichan/e22b3ecfa21b93eedaa799b6f5174074 to your computer and use it in GitHub Desktop.
deep clone when there's circlular reference
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