Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce immutability or partial immutability that doesn't fail silently

Is there a way to enforce partial immutability on an object that will throw an error if someone tries to mutate it?

For example, let obj = {a: 1, b: 2} and I want obj.a and obj.b to be immutable but to still allow more keys to be added to obj, i.e to allow obj.c = 3.

I thought of nesting properties in sub-objects and using Object.freeze like so:

let obj = {subObj:{a: 1, b:2}}; 
Object.freeze(obj.subObj);

But it appears that it fails silently afterward, i.e obj.subObj.a = 3 doesn't mutate a but doesn't give any indication of a problem either. Is there a way to force it to throw an error?

like image 466
shinzou Avatar asked Feb 04 '23 11:02

shinzou


1 Answers

The simple way to do this would be with getters that return static values and setters that throw errors.

let obj = {
  get a() {
    return 1;
  },
  set a(val) {
    throw new Error('Can\'t set a');
  },
  get b() {
    return 2;
  },
  set b(val) {
    throw new Error('Can\'t set b');
  }
};
obj.c = 3; // works
console.log(obj);
obj.a = 4; // throws an error
like image 148
lonesomeday Avatar answered Feb 07 '23 11:02

lonesomeday