Immutability
Functional programming
Pure functions
What is a perfect function
- Doesn't depend on higher scope
- Always returns the same results with the same arguments
- Can be used in memoization pattern
- Can be used in different environment
- Easy to test
- Can be run in parallel
function (a: number[]): number {
return a.reduce((akk, num) => akk + num, 0);
}
Can it be run in parallel?
function (a: number[]): number {
return a.reduce((akk, num) => akk + num, 0);
}
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
Immutability
Immutable in JS
- Number
- String
- null
- undefined
- Boolean
- Symbol
const
freeze and seal
defineProperty
Object.defineProperty(obj, 'key', {
enumerable: false,
configurable: false,
writable: false,
value: 'static'
});
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
How change it?
Copy everything!
Use immutable data structures
Array
LinkedList
Hashmap and set
Tire Tree
Operations
- Search
- Insert
- Delete
Tire hash map
How can we get it?
Map or Set?
Immutable.js
Immutability
By Vladimir
Immutability
- 94