immutable
Effecient immutable data-structures in javascript.
Why?
Mutability causes headaches; immutability soothes them. JavaScript's Object and Array are crying out for immutable counterparts to complement first-class functions.
Support
Example
var im = require('immutable')
var person = im.object({ firstName: 'hugh', secondName: 'jackson' })
var personWithAge = person.assoc({ age: 24 })
person.has('age')
personWithAge.has('age')
personWithAge.get('age')
Install
npm install immutable
immutable.object
Create an empty immutable object:
var o = im.object()
Or define the initial set of properties:
var you = im.object({ wise: true, willUseThisLib: true })
.assoc
Create a new immutable object with a property added or updated:
var emptyObject = im.object()
var basicPerson = o.assoc('human', true)
Or pass an object to define multiple properties at once:
var personRecord = basicPerson.assoc({ name: 'joe bloggs', age: 34 })
.get
Get a property:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.get('age')
It works on numeric keys too, although you're more likely to use an array for this:
var readingList = im.object({ 1: 'Operating System Design: The Xinu Approach' })
readingList.get(1)
.has
Check if an immutable object has a property:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.has('name')
person.has('discography')
.dissoc
Create a new immutable object without a property:
var person = im.object({ name: 'joe bloggs', age: 34 })
var personShyAboutAge = person.dissoc('age')
personShyAboutAge.get('age')
.mutable / .toJSON
Create a regular JavaScript object from an immutable one:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.mutable()
The .toJSON
alias allows immutable objects to be serialised seamlessly with regular objects:
var favouritePeople = {
joe: im.object({ name: 'joe bloggs', age: 34 })
}
var data = JSON.stringify(favouritePeople)
data // = { joe: { name: 'joe bloggs', age: 34 } }
immutable.array
Create a new immutable array:
var arr = im.array()
or with initial values:
var arr = im.array([1, 2, 3, 4])
.assoc/.dissoc/.get/.has
Work identically in imutable.array as they do in immutable.object, except that they keep the .length property of the array up to date.
.length
Check the 'length' of an immutable array:
var arr = im.array([1, 2, 3])
arr.length
.mutable / .toJSON
Create a regular JavaScript object from an immutable one:
var todo = im.array(['write README', 'run tests on all supported platform'])
todo.mutable()
The .toJSON
alias allows immutable objects to be serialised seamlessly with regular objects:
var lists = {
todo: im.array(['write README', 'run tests on all supported platform'])
}
var data = JSON.stringify(lists)
data // = { todo: ['write README', 'run tests on all supported platform'] }