js-lenses

2.0.1 • Public • Published

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 lense
  • L.ofPath('path', 'to', 'value') — create lense from path
  • L.get(lense, target) — get value
  • L.set(lense, value, target) — set value
  • L.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 🎓

Readme

Keywords

Package Sidebar

Install

npm i js-lenses

Weekly Downloads

76

Version

2.0.1

License

MIT

Last publish

Collaborators

  • roman01la