js-lenses
v2.0.1
Published
Pure, composable, immutable getters and setters for plain JavaScript data structures.
Downloads
33
Readme
js-lenses
Pure, composable, immutable getters and setters for plain JavaScript data structures.
data → (⟩ a → ƒ(a) ⟨) → data
What is it?
Functional lenses are pure functional references into data structures.
Given
var a = { b: { c: { d: 'd' } } };
Imperative refereces
/* reference to value { d: 'd' } inside of a */
a['b'].c;
a['b'].c; // get
a['b'].c = 1; // set
Functional references with js-lenses
/* reference to value { d: 'd' } inside of a */
var l = L.ofPath('a', 'b', 'c');
L.get(l, a); // get
L.set(l, 1, a); // set
The difference between these two approaches is that lenses are easily composable and immutable.
Installation
npm i js-lenses
Usage
L.of('propName')
— create lenseL.ofPath('path', 'to', 'value')
— create lense from pathL.get(lense, target)
— get valueL.set(lense, value, target)
— set valueL.update(lense, fn, target)
— update value by applying function to it
import L from 'js-lenses';
var person = { name: 'John', children: { boys: [{ name: 'John'}, { name: 'Dirk' }] }};
var nameLense = L.of('name'); // create lense
L.get(nameLense, person); // extract lense value out of data
L.set(nameLense, 'Jim', person); // set value into data structure
var childrenLense = L.compose(L.of('children'), L.of('boys')); // compose lenses
var firstNameChildLense = L.ofPath('children', 'boys', 0, 'name'); // or create one from path
L.update(childrenLense, (children) => children.map((child) => (child.age = 11, child)) , person); // update lense value
Why?
For learning purpose 🎓