From e9c41fed036dd6e6c28ae868d9d3ee7ccf5f0d44 Mon Sep 17 00:00:00 2001 From: Lucas Winther Date: Wed, 28 Oct 2026 23:39:46 +0100 Subject: [PATCH] fix(js): deepFreeze recurses below already-frozen parents Co-Authored-By: Claude Sonnet 5.5 --- js/solutions/util.js | 11 ++++++----- js/src/util.js | 2 +- js/test/m01-util.test.js | 10 ++++++++++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/js/solutions/util.js b/js/solutions/util.js index d273528..b5fe610 100644 --- a/js/solutions/util.js +++ b/js/solutions/util.js @@ -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 } diff --git a/js/src/util.js b/js/src/util.js index 6e6f10f..5c8c743 100644 --- a/js/src/util.js +++ b/js/src/util.js @@ -15,5 +15,5 @@ export const pipe = (x, ...fns) => todo('m01') /** `compose(f, g)(x)` is `f(g(x))`: functions applied right to left. */ export const compose = (...fns) => todo('m01') -/** Freeze `obj` and everything reachable from it, then return it (same object). */ +/** Freeze `obj` and everything reachable from it (even below already-frozen parents; cycles are fine), then return it (same object). */ export const deepFreeze = (obj) => todo('m01') diff --git a/js/test/m01-util.test.js b/js/test/m01-util.test.js index 56160ef..62ba46a 100644 --- a/js/test/m01-util.test.js +++ b/js/test/m01-util.test.js @@ -45,3 +45,13 @@ test('m01 deepFreeze returns the same object it was given', () => { const o = {} assert.equal(deepFreeze(o), o) }) +test('m01 deepFreeze reaches unfrozen children of an already-frozen parent', () => { + const o = deepFreeze({ a: Object.freeze({ b: { c: 1 } }) }) + assert.ok(Object.isFrozen(o.a.b)) +}) +test('m01 deepFreeze handles cyclic objects', () => { + const o = { child: {} } + o.child.parent = o + deepFreeze(o) + assert.ok(Object.isFrozen(o) && Object.isFrozen(o.child)) +})