Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Makes a class and its instances imutable
LiveScript JavaScript
Branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
spec
src
.gitignore
.npmignore
.travis.yml
Gruntfile.js
README.md
imutable.sublime-project
package.json

README.md

imutable

Build Status

Makes a class and its instances imutable

Install

$ npm install imutable [--save]

Usage

require! \imutable

ImClass = imutable class
  (@value = 0) ->

im-obj = new ImClass 1
console.log im-obj.value # 1

im-obj.value = 2 # does nothing, or throws error in strict mode
console.log im-obj.value # 1, if not in strict mode

Modes

By default, imutable freezes the class, the prototype, as well as any new instance. So, no properties can be changed, removed or added to any of these.

There are also some advanced use cases when a property/method depends on another object. For example:

dep = value: 1
ImClass = imutable class
  -> @dep = dep
  dep-value:~
    -> @dep.value
    (v) -> @dep.value = v

im-obj = new ImClass

console.log im-obj.dep-value # 1
im-obj.dep-value = 2
console.log im-obj.dep-value # 2 !!!

So, this object is not so imutable after all. That's because Object.freeze does not remove property setters.

In this case you can use imutable \strict, which does exactly that, removes all setters.

Strict

In the above example, by creating the class like

ImClass = imutable \strict class
...

the line

im-obj.dep-value = 2

would have no effect (or throw an error if strict)


Another example using a depending object is when you use methods for getters and setters instead of property accessors

dep = value: 1
ImClass = imutable class
  -> @dep = dep
  set-dep-value: (v) -> @dep.value = v
  get-dep-value: -> @dep.value

im-obj = new ImClass

console.log im-obj.get-dep-value! # 1
im-obj.set-dep-value 2
console.log im-obj.get-dep-value! # 2 !!! again

Then the solution would be to make all of the children (recursively) imutable. That's what \recursive mode does

Recursive

Creating the class like this

ImClass = imutable \recursive class

makes all the object's successors imutable. So calling im-obj.set-dep-value 2 would again do nothing.

Something went wrong with that request. Please try again.