Deep Freeze With Cycle Protection
Recursively freeze arrays and objects while tolerating cycles, accessors and typed arrays that cannot be frozen with elements.
Code
export function deepFreeze(value, seen = new WeakSet()) {
if (value === null || (typeof value !== "object" && typeof value !== "function")) {
return value;
}
if (seen.has(value)) return value;
seen.add(value);
if (ArrayBuffer.isView(value)) return value;
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor && "value" in descriptor) {
deepFreeze(descriptor.value, seen);
}
}
return Object.freeze(value);
}How it works
Deep Freeze With Cycle Protection keeps everything in the function deepFreeze.
Iteration happens inside for (const key of Reflect.ownKeys(value)) — everything outside it runs once.
Putting it to use
The main signature reads export function deepFreeze(value, seen = new WeakSet()
The surface worth importing is deepFreeze; the helpers around it are private to the snippet.
Core lines
if (ArrayBuffer.isView(value)) return value;
if (seen.has(value)) return value;
return Object.freeze(value);
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `deepFreeze` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.