Last active
May 14, 2019 08:26
-
-
Save afterburn/68a97b6eb0a65d00038f17a30b6ecd46 to your computer and use it in GitHub Desktop.
Recursively freezes an object to make it fully immutable.
This file contains hidden or 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
function deepFreeze (obj) { | |
Object.freeze(obj) | |
Object.values(obj).forEach((value) => { | |
if (typeof value === 'object') { | |
deepFreeze(value) | |
} | |
}) | |
} |
This file contains hidden or 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
const user = { | |
name: 'john', | |
wallet: { | |
balance: 100 | |
} | |
} | |
deepFreeze(user) | |
user.name = 'bob' | |
user.wallet.balance = 99999 | |
console.log(user) | |
// { | |
// name: 'john', | |
// wallet: { | |
// balance: 100 | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment