Introduction
Saber is a modular and functional library oriented with methods which operate on immutable data. In this chapter we will look over a very basic example to give you insight about how to use the library.
Installing as NPM package
npm install @berakocc/saber
A Basic Example
1
2
3
4
5
6
7
8
9
10
import { SaberObject } from '@berakocc/saber'

// You can create Saber objects
// with factory methods
const saberObject = SaberObject.create({
name: 'Adam Smith',
age: 38
})
saberObject.add('hasAJob', true)
console.log(saberObject.value)
Output
Object {
name: "Adam Smith"
age: 48,
}
Understanding Immutability
If data is immutable it is unchangeable. In JavaScript most of the data types don't satisfy this rule. Except primitive data types like numbers and String(which is a special case).
Why should you use it?
The main reason to use immutable types is preventing data from vanishing. When you change state in React or any other framework, it is recommended to change state values by immutable operations since it makes easier to record changing state and diagnosing errors if they ever occur.
Immutability
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { Component } from 'react'

class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
todos: []
}

add = (todo) => {
this.setState([this.state.todos, todo])
}
}
Creating SaberObject
There are two ways of creating SaberObject: classic object initialisation and static factory method Although they do the same job, there is a subtle difference. Static factory method has tighter type definition. Hence using it would be more appropriate.
Initialising SaberObject
1
2
3
4
5
6
import { SaberObject } from '@berakocc/saber'

const saberObjectWithDefaultInitialisation
= new SaberObject({ id: 2 })
const SaberObjectWithFactoryMethod
= SaberObject.create({ id: 3 })
Note
Always use create method over normal object creation.
Creating SaberArray
Same as SaberObject with one little exception. You can denote types with diamond notation You have the choice not to. But for the sake of clarity, this is better. Also using arrays with one type makes your code less error prone.
Initialising SaberArray
1
2
3
4
import { SaberArray } from '@berakocc/saber'

const SaberObjectWithFactoryMethod
= SaberArray.create<number>([1, 2, 3])
Note
Always use create method over normal object creation.