Skip to content

Instantly share code, notes, and snippets.

@zorgick
Forked from ositowang/ultimateDeepClone.js
Created January 3, 2022 20:41
Show Gist options
  • Save zorgick/5386d377867f713ede73506cf47ed63c to your computer and use it in GitHub Desktop.
Save zorgick/5386d377867f713ede73506cf47ed63c to your computer and use it in GitHub Desktop.
Ultimate version solving circular dependency with weakMap
/**
* Ultimate version solving circular dependency with weakMap
* Problems:
* 1. Symbols not covered
*
* @param {Object} sourceObj
* @param {WeakMap} [hash=new WeakMap()]
* @returns
*/
var deepCloneUltimate = (sourceObj, hash = new WeakMap()) => {
if (typeof sourceObj !== 'object' && sourceObj !== null) {
return sourceObj;
}
//if we already had the object, we get it
if (hash.has(sourceObj)) {
return hash.get(sourceObj);
}
let result = Array.isArray(sourceObj) ? [] : {};
hash.set(sourceObj, result);
for (let key in sourceObj) {
if (Object.prototype.hasOwnProperty.call(sourceObj, key)) {
if (typeof sourceObj[key] !== 'object' && sourceObj[key] !== null) {
result[key] = deepCloneUltimate(sourceObj[key], hash);
} else {
result[key] = sourceObj[key];
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment