Immutable JavaScript data structures, backwards-compatible with arrays, objects
github.com
github.com
var array = Immutable(["totally", "immutable", {hammer: "Can’t Touch This"}]);
array[1] = "I'm going to mutate you!"
array[1] // "immutable"
I find it a little weird that the result of trying to mutate an immutable object is to silently fail the mutation. Couldn't this hide errors where the developer expects something to mutate because they didn't realize it was immutable? Shouldn't it throw instead?Edit: After reading the documentation more thoroughly, I saw "All the methods that would normally mutate the data structures instead throw ImmutableError." Looks like the first section isn't actually accurate then?
The reason the docs say "the methods that would normally mutate..." is that in the specific case of methods (e.g. array.push()), the library can and does override them to throw exceptions.
I would certainly prefer to make that example throw an exception, but it's simply not possible in JS. :)
I wonder what the reason behind that is, if you're feeling extra motivated you could even look into having a conversation with the folks who decide what future versions of JS look like to add something like it. I am a huge proponent of immutability and can see how being able to override array element assignment behaviors would improve your library.
Object.defineProperty(x,'foo',{set:function() { throw new Error(69) }})https://gist.github.com/vjeux/6b390e6a6bb51e24b646
__DEV__ = true;
var array = ['a', 'b', 'c']
deepFreezeAndThrowOnMutationInDev(array)
array[0] = 10;
Error: You attempted to set the key `0` with the value `10` on an object that is meant to be immutable and has been frozen.If you want an implementation of these ideas in JS, Immutable.js [0] or Mori [1] are the leading libraries. seamless-immutable doesn't use these techniques, so it probably wouldn't perform well on large data sets. The benefit of it is that the immutable objects can be used as drop-in replacements for their native JS equivalents in some situations.
Full disclosure: I've contributed to Immutable.js
This one is directly on js objects (seamless-immutable).
I like the look of this one better. IMHO Facebook's approach will lead to confusion and subtle errors when their immutables are mixed up with normal objects and arrays. Personally I think this is think that's an unwise decision that will lead to confusion and subtle errors.