lens.ts
TypeScript Lens implementation
Lens?
Lens is composable abstraction of getter and setter. For more detail of Lens, I
recommend reading the following documents.
Install
Via npm:
npm i lens.ts
Usage
import { lens } from 'lens.ts';
type Person = {
name: string;
age: number;
accounts: Array<Account>;
};
type Account = {
type: string;
handle: string;
};
const azusa: Person = {
name: 'Nakano Azusa',
age: 15,
accounts: [
{
type: 'twitter',
handle: '@azusa'
},
{
type: 'facebook',
handle: 'nakano.azusa'
}
]
};
const personL = lens<Person>();
personL.k('name')
personL.k('accounts')
personL.k('hoge')
personL.k('accounts').i(1)
personL.i(1)
lens<Person>().k('accounts').i(1).compose(
lens<Account>().k('handle')
);
personL.k('accounts').i(0).k('handle').get(azusa)
personL.k('name').set('中野梓')(azusa)
personL.k('age').update(x => x + 1)(azusa)
You can find similar example code in test/test.ts
API
lens.ts
exports the followings:
import {
lens,
Lens,
KeyLens,
IndexLens
} from 'lens.ts';
lens
A function lens
is a factory function for an identity lens for a type. It
returns a Lens
instance.
lens<Person>()
Lens<T, U>
An instance of Lens
can be constructed with a getter and setter for a
source type T
and a result type U
.
class Lens<T, U> {
constructor(
public get: (target: T) => U,
public set: (value: U) => (target: T) => T
) { ... }
}
Lens
provides the following methods.
.get(src: T): U
Retrives an actual value from an actual source.
let x: T;
let lens: Lens<T, U>;
lens.get(x)
.set(val: U): (src: T) => T
Returns a setter function returning a new object with the provided value already
set. This function is immutable.
let x: T;
let lens: Lens<T, string>;
let y: T = lens.set('hello')(x);
lens.get(y)
.update(f: (val: U) => U): (src: T) => T
Same as .set()
, but with a modifier instead of a value.
let y: T;
let lens: Lens<T, string>;
let z: T = lens.update(str => str + ', world')(y);
lens.get(z)
.compose(otherLens: Lens<U, V>): Lens<U, V>
Composes 2 lenses into one.
let lens1: Lens<T, U>;
let lens2: Lens<U, V>;
lens1.compose(lens2)
.k(key: string)
A helper method to narrow the lens for a property of U
.
type Person = { name: string };
let lens: Lens<Person, Person>;
lens.k('name')
lens.compose(new KeyLens<Person, 'name'>('name'))
.i(index: number)
A helper method to narrow the lens for an element of an array U
. A type error
is thrown if U
is not an array.
let lens: Lens<T, Array<E>>;
lens.i(10)
lens.compose(new IndexLens<E>(10))
KeyLens
, IndexLens
They are exported for the references of the .k()
and .i()
methods above, but
it's not recommended using them by themselves. Please use the helper methods.
lens().k('name')
lens().i(10)
License
MIT