Created
January 27, 2022 05:36
-
-
Save gartz/81ad7cf68ad89ec3c513e55396bc0da7 to your computer and use it in GitHub Desktop.
js deepFreeze
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
/** | |
* Will deep freeze any object recursively. And it supports circular references. | |
*/ | |
function deepCloneAndFreeze(arg) { | |
const circularFrozenRefMap = new WeakMap(); | |
function deepCloneAndNativeFreeze(arg) { | |
const clone = Array.isArray(arg) ? [] : {}; | |
circularFrozenRefMap.set(arg, clone); | |
const isObject = input => typeof input === 'object'; | |
const isCircularDependency = object => circularFrozenRefMap.has(object); | |
const deepFreezeWhenObject = key => { | |
const value = arg[key]; | |
if (isObject(value)) { | |
if (isCircularDependency(value)) { | |
clone[key] = circularFrozenRefMap.get(value); | |
} else { | |
clone[key] = deepCloneAndNativeFreeze(value); | |
} | |
} else { | |
clone[key] = value; | |
} | |
}; | |
Object.getOwnPropertySymbols(arg).forEach(deepFreezeWhenObject); | |
Object.getOwnPropertyNames(arg).forEach(deepFreezeWhenObject); | |
return Object.freeze(clone); | |
} | |
return deepCloneAndNativeFreeze(arg); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment