Last active
April 26, 2022 03:37
-
-
Save crazy4groovy/fcb6873d977d0c3f163a39bdc1c8c470 to your computer and use it in GitHub Desktop.
Using a Proxy object to enforce immutability, instead of Object.freeze (JavaScript)
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
// credit: https://www.30secondsofcode.org/articles/s/js-immutable-object-proxy | |
const term = { | |
id: 1, | |
value: 'hello', | |
properties: [{ type: 'usage', value: 'greeting' }], | |
}; | |
const immutable = obj => | |
new Proxy(obj, { | |
get(target, prop) { | |
return typeof target[prop] === 'object' | |
? immutable(target[prop]) | |
: target[prop]; | |
}, | |
set() { | |
throw new Error('This object is immutable.'); | |
}, | |
}); | |
const immutableTerm = immutable(term); | |
const immutableProperty = immutableTerm.properties[0]; | |
immutableTerm.name = 'hi'; // Error: This object is immutable. | |
immutableTerm.id = 2; // Error: This object is immutable. | |
immutableProperty.value = 'pronoun'; // Error: This object is immutable. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment