MC Hammer
This is a really simple library for creating sort-of-immutable data structures in Javascript. It's called "MC Hammer" because you "can't touch this". Why might you want to use it? Mainly because you are interested in referential transparency and want something to remind you about immutability.
This library does not provide deep immutability of built-ins like seamless-immutable or a rich API like Immutable. What it gives you is an easy way to create and (non-destructively) update objects that have read-only properties and methods.
Installation
This library is available through NPM or Bower and it is packaged as a UMD bundle.
npm install mchammer
or
bower install mchammer
and if you are using node/commonjs
var Model = Model Foo =
or AMD
or neither
var Foo = mchammer
Basics
You create a model by defining what properties are allowed and their defaults as well as any methods.
var Model = Model var Writer =
Then you can create instances of the new model, specifying only the properties that have a value different from the defaults.
var writer = name: 'Stephen King' number_of_books: 54 console // "Stephen King"console // "Derp!"writer // "Derp!"
You can't change any of the properties.
writersomething = 'Boo!' // TypeError("Cannot assign to read only property 'something' of [object Object]")
But you can easily create a modified copy by specifying the properties you want to change
var the_real_writer = writerthe_real_writer // 'Boo!'
Fields
To define the fields a Model has, use the fields
options.
var Foo = foo = console // 'Steve'
Fields can also be functions, in which case they are transformers for whatever value is passed in during instantiation, including undefined
.
var Foo = foo1 = foo2 = name: 'Blobface' console // 'Nameless'console // 'Steve Blobface'
Fields are immutable. Don't bother trying to set them.
foo2name = 'Andrea Blobface' // TypeError("Cannot assign to read only property 'name' of [object Object]")
Also, if you didn't define a field when you created the model, you can't do it later.
var Foo = foo1 = foo2 = stuff: 'things' // Error('Unknown field "stuff"'), foo3 = foo1 // Error('Unknown field "skidoo"')
Inheritance
Existing models can be extended.
var Model = Model var Instrument = var Guitar = Model var Martin = Model var martin_guitar = martin_guitar // 'Twang Twang'martin_guitarconstructor == Martin // trueModel // trueModel // true
Comparisons
You can Deeply compare two Model
instances like so
var SweetMove = spin = twirl = cartwheel = name: 'cartwheel' danger_level: 5 spin // truespin // false
You can also compare only based on a subset of properties, like this:
var backbend = name: 'backbend' danger_level: 5 cartwheel // falsecartwheel // true
Contributing
If you see an open issue you want to tackle, be my guest. If you have a problem or feature suggestion, please create a new issue. Thanks!