Skip to content

Instantly share code, notes, and snippets.

@edgarberm
Last active June 21, 2017 10:29
Show Gist options
  • Save edgarberm/92a13425e06327b5390cd146e7c0b3ce to your computer and use it in GitHub Desktop.
Save edgarberm/92a13425e06327b5390cd146e7c0b3ce to your computer and use it in GitHub Desktop.
Deep freeze ❄️
/**
* Freeze nested objects
*
* const dude = deepFreeze({
* name: 'John',
* lastname: 'Doe',
* address: {
* street: 'Wall Street',
* number: '62'
* }
* })
*
* dude.address.street = 'Broadway' // TypeError: Cannot assign to read only property 'name' of object '#<Object>'
**/
const isObject = (val) => val && typeof val === 'object'
function deepFreeze (obj) {
if (isObject(obj) && !Object.isFrozen(obj)) {
Object.keys(obj).forEach(name => deepFreeze(obj[ name ]))
Object.freeze(obj)
}
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment