Skip to content

Instantly share code, notes, and snippets.

@stereobooster
Last active March 22, 2019 09:39
Show Gist options
  • Save stereobooster/0151a43500363dd8baa982c170c069ce to your computer and use it in GitHub Desktop.
Save stereobooster/0151a43500363dd8baa982c170c069ce to your computer and use it in GitHub Desktop.
/**
* 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