-
-
Save zorgick/5386d377867f713ede73506cf47ed63c to your computer and use it in GitHub Desktop.
Ultimate version solving circular dependency with weakMap
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
/** | |
* 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