Focalize
Functional Lenses for Javascript
Focalize provides a composable set of functionality to handle immutable data updates.
Example
In order to update state immutably we might use the object spread
operator and map
/ reduce
over arrays as follows:
// vanilla-reducer.jsconst reducer = { };
Focalize increases readibility by providing a composable API that can be used to both query and update data immutably. The same example using Focalize becomes.
// lensed-reducer.js; const reducer = { };
Also note that in the top example if the employee does not exist or is already terminated we still end up with a new state object.
Focalize performs updates economically, we retain the existing
objects if no changes are required, and hence we can use
state === result
to check for changes.
; const state = departments: name: 'Research' employees: staffId: '101' name: 'Francis' terminated: false staffId: '123' name: 'Bob' terminated: true ; // Bob already terminated, no changes required; // => OK!
For more examples see the test
folder for basic and advanced usage
as well as usage for each operator.
References
- Monocle
- Scalaz
- Shapeless
- Albert Steckermeier (1 July 2015). "Lenses in Functional Programming".
- Twan Van Laarhoven. "Lenses: viewing and updating data structures in Haskell"