Bubble Foundry


Immutable Javascript

by Peter.

Something I quickly whipped up the other day, which you can find on GitHub as a Gist.

Wish you had some immutability in Javascript? Now you can!

var t = {a: 1, b: 2}.immutable();
console.log(t.a, t.b);
try {
  t.a = 3; // ->  Uncaught Error: a is immutable and cannot be modified.
} catch (e) {
  console.log(e);
}
var t2 = t.copy({a: 3});
console.log(t2.a, t2.b);
t2.mutable();
t2.a = 1;
console.log(t2.a, t2.b);

As you can see, the methods immutable, copy, and mutable are added to Object.prototype. This is done using custom getters and setters to mask the original properties, so it only works with objects that expose them and not things like strings. Of course, if you figure out how to get this to work for other Javascript datatypes, please let me know!