fix(js): deepFreeze recurses below already-frozen parents
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
22c221a042
commit
e9c41fed03
@@ -18,12 +18,13 @@ export const compose = (...fns) => (x) => fns.reduceRight((acc, f) => f(acc), x)
|
||||
/**
|
||||
* Freeze `obj` and everything reachable from it, then return it.
|
||||
* Freezing is the one deliberate "mutation" here: it makes later accidental mutation throw.
|
||||
* We recurse even into children that are already frozen (a frozen parent can still hold
|
||||
* unfrozen children). `ancestors` is the path from the root to `obj`; passing it down
|
||||
* (instead of keeping a shared "seen" set) stops cyclic structures without any mutable state.
|
||||
*/
|
||||
export const deepFreeze = (obj) => {
|
||||
export const deepFreeze = (obj, ancestors = []) => {
|
||||
if (obj === null || typeof obj !== 'object' || ancestors.includes(obj)) return obj
|
||||
Object.freeze(obj)
|
||||
// Freezing before recursing means cyclic structures stop at the already-frozen node.
|
||||
Object.values(obj).forEach((v) => {
|
||||
if (v !== null && typeof v === 'object' && !Object.isFrozen(v)) deepFreeze(v)
|
||||
})
|
||||
Object.values(obj).forEach((v) => deepFreeze(v, [...ancestors, obj]))
|
||||
return obj
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user