@logankeenan/immutable-model

A basic javascript class which encourages immutability.

Stats

StarsIssuesVersionUpdatedCreatedSize
@logankeenan/immutable-model
0.0.143 years ago4 years agoMinified + gzip package size for @logankeenan/immutable-model in KB

Readme

Immutable Model

Greenkeeper badge

Build Status npm version

A Javascript class which encourages immutability by not allowing setters, keeping state private, and only allowing state to exist for defined getters.

Warning: This module is in active development. Breaking changes may occur prior to 1.0.0 release.

Why?

Other modules exist to encourage immutability, but come at a cost of coupling to an API. This module was created to allow developers to use standard javascript classes and encourage immutability.

Examples

import ImmutableModel from '@logankeenan/immutable-model';

class Person extends ImmutableModel {
    get firstName() {
        return this._properties.firstName;
    }
}

const person = new Person({firstName: "john"});

console.log(person.firstName);  // john
console.log(person._properties); // { firstName: 'john' }

Creating a class with a setter will throw an error.

import ImmutableModel from '@logankeenan/immutable-model';

class Person extends ImmutableModel {
    set age(age) {
        return;
    }
}

const loganPerson = new Person({age: 50});
//throws Error: Set properties do not encourage immutability. Set property defined for age.

Only properties with defined getters will be stored.

import ImmutableModel from '@logankeenan/immutable-model';

class Person extends ImmutableModel {
    get age() {
        return this._properties.age;
    }
}

const person = new Person({age: 50, firstName: 'john'});
console.log(person._properties); // { age: 50 }

The _properties value is immutable.

import ImmutableModel from '@logankeenan/immutable-model';

class Person extends ImmutableModel {
    get age() {
        return this._properties.age;
    }
}

const person = new Person({age: 50});
person._properties.age = 100;
//Cannot assign to read only property 'age' of object '#<Object>'

See examples for more usages

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.