Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
*/
function deepFreeze<T>(object: T, path?: string): Readonly<T> {
const propNames = Object.getOwnPropertyNames(object);
let latest;
try {
for (const name of propNames) {
// @ts-ignore - do not verify implementation
const value = object[name];
latest = name;
// @ts-ignore - do not verify implementation
object[name] = value && typeof value === "object" ? deepFreeze(value, path !== undefined ? `${path}/${latest}` : path) : value;
}
} catch (e) {
// ignore if it was freezed before
if (path) console.log(`Can't freeze ${path}/${latest}`);
}
return Object.freeze(object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment