Skip to content

Instantly share code, notes, and snippets.

@ositowang
Created April 1, 2019 01:22
Show Gist options
  • Select an option

  • Save ositowang/7fa8ee5aa881c850fa536586128b2cad to your computer and use it in GitHub Desktop.

Select an option

Save ositowang/7fa8ee5aa881c850fa536586128b2cad 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