Effecient immutable data-structures in javascript.
Mutability causes headaches; immutability soothes them. JavaScript's Object and Array are crying out for immutable counterparts to complement first-class functions.
var im = require('immutable')
var person = im.object({ firstName: 'hugh', secondName: 'jackson' })
var personWithAge = person.assoc({ age: 24 })
person.has('age') //= false
personWithAge.has('age') //= true
personWithAge.get('age') //= 24
npm install immutable
Create an empty immutable object:
var emptyObject = im.object()
Or define the initial set of properties:
var person = im.object({ name: 'joe bloggs', age: 34 })
Create a new immutable object with a property added or updated:
var emptyObject = im.object()
var basicPerson = emptyObject.assoc('human', true)
Or pass an object to define multiple properties at once:
var personRecord = basicPerson.assoc({ name: 'joe bloggs', age: 34 })
Get a property:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.get('age') //= 34
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) //= 'Operating System Design: The Xinu Approach'
Check if an immutable object has a property:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.has('name') //= true
person.has('discography') //= false
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') //= undefined
Create a regular JavaScript object from an immutable one:
var person = im.object({ name: 'joe bloggs', age: 34 })
person.mutable() //= { name: 'joe bloggs', age: 34 }
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 } }
Create a new immutable array:
var arr = im.array()
or with initial values:
var arr = im.array([1, 2, 3, 4])
Work identically in imutable.array as they do in immutable.object, except that they keep the .length property of the array up to date.
Check the 'length' of an immutable array:
var arr = im.array([1, 2, 3])
arr.length //= 3
Create a regular JavaScript object from an immutable one:
var todo = im.array(['write README', 'run tests on all supported platform'])
todo.mutable() //= ['write README', 'run tests on all supported platform']
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'] }