0.0.14 • Published 7 years ago
@logankeenan/immutable-model v0.0.14
Immutable Model
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