Last active
March 22, 2019 09:39
-
-
Save stereobooster/0151a43500363dd8baa982c170c069ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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