Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active April 26, 2022 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/fcb6873d977d0c3f163a39bdc1c8c470 to your computer and use it in GitHub Desktop.
Save crazy4groovy/fcb6873d977d0c3f163a39bdc1c8c470 to your computer and use it in GitHub Desktop.
Using a Proxy object to enforce immutability, instead of Object.freeze (JavaScript)
// 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