Warning: API Unstable (even more so than most < 1.0.0 releases)
immutable
immutable neatly packages immutable equivalents to JavaScript's Objects and Arrays.
Why?
Mutability causes headaches; immutability soothes them. JavaScript's Object and Array are crying out for immutable counterparts to complement first-class functions.
Support
Current support is limited to ECMAScript 5 compliant environments; although ECMAScript 3 compliance is a goal of this project.
Example
var i = require('immutable'),
person = i.object({ firstName: 'hugh', secondName: 'jackson' })
var personWithAge = person.set({ age: 24 })
person.has('age')
personWithAge.has('age')
personWithAge.get('age')
Install
npm install immutable
immutable.object([Object]) -> object
Creates an empty object, or sets the attributes if an object is passed.
var o = i.object()
var you = i.object({ wise: true, willUseThisLib: true })
.set(String, Value) OR .set(Object) -> object
Returns a new object with the additional attribute(s).
var o = i.object()
var changed = o.set('x', 3).set({ y: 4, z: 5 })
changed.has('x')
changed.get('y')
.get(String) -> value
Gets an attribute.
var o = i.object({ x: 3, y: 4 })
o.get('x')
.has(String) -> Boolean
Returns true or false; same as key in object
for regular objects:
var o = i.object({ x: 3, y: 4 })
o.has('x')
o.has('z')
.remove(String) alias: .delete(String)
-> object
Returns a new object
with the key removed.
var o = i.object({
foo: 'bar',
baz: 'quux'
})
var updated = o.remove('foo').remove('baz')
updated.has('foo')
o.has('foo')
.transient() -> Object
Returns a seperate, mutable object with the same attrs.
var o = i.object({
foo: 'bar',
baz: 'quux'
})
var trans = o.transient()
delete trans.foo
o.has('foo')
immutable.array(Array) -> array
Shares the same API as immutable.object
, except:
.transient() -> Array
Returns a seperate, mutable array with the same attrs.
var arr1 = i.array([1, 2, 3]),
arr2 = arr1.transient()
arr2.splice(1)
arr1[1] !== arr2[1]
Native Methods
The following native methods return a new instance of i.array:
- map
- sort
- filter
- splice
- slice
- reverse
- concat
- pop
- push
- shift
- unshift
The following native methods work as expected for a regular array:
- toString
- toLocaleString
- join
- forEach
- indexOf
- lastIndexOf
- every
- some
- reduce
- reduceRight
Resources
Based on Bagwell (2001), and Clojure's immutable implementation of a Hash Array Mapped Trie.