Last active
June 21, 2017 10:29
-
-
Save edgarberm/92a13425e06327b5390cd146e7c0b3ce to your computer and use it in GitHub Desktop.
Deep freeze ❄️
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
/** | |
* 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