• Stars
    star
    142
  • Rank 258,495 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

TypeScript Lens implementation with property proxy

lens.ts travis-ci

TypeScript Lens implementation with property proxy

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 a factory function for lens
import { lens } from 'lens.ts';

type Person = {
  name: string;
  age: number;
  accounts: Array<Account>;
};

type Account = {
  type: string;
  handle: string;
};

let azusa: Person = {
  name: 'Nakano Azusa',
  age: 15,
  accounts: [
    {
      type: 'twitter',
      handle: '@azusa'
    },
    {
      type: 'facebook',
      handle: 'nakano.azusa'
    }
  ]
};

// create an identity lens for Person
let personL = lens<Person>();

// key lens with k()
personL.k('name') // :: Lens<Person, string>
personL.k('accounts') // :: Lens<Person, Array<Account>>
personL.k('hoge') // type error, 'hoge' is not a key of Person
personL.k('accounts').k(1) // :: Lens<Person, Account>
personL.k(1) // type error, 'i' cannot be used for non-array type

// You can use property proxy to narrow lenses
personL.name // :: Lens<Person, string>
personL.accounts // :: Lens<Person, Array<Account>>
personL.accounts[1] // :: Lens<Person, Account>
personL.hoge // type error

// get and set with Lens
personL.accounts[0].handle.get()(azusa) // -> '@azusa'
personL.accounts[0].handle.set('@nakano')(azusa) // -> { ... { handle: '@nakano' } ... }
personL.age.set(x => x + 1)(azusa) // -> { age: 16, ... }

// Lens composition
let fstAccountL = lens<Person>().accounts[0] // :: Lens<Person, Account>
let handleL = lens<Account>().handle // :: Lens<Account, string>
fstAccountL.compose(handleL) // :: Lens<Person, string>

// Getter/Setter composition
fstAccountL.get(handleL.get())(azusa) // -> '@azusa'
fstAccountL.set(handleL.set('@nakano'))(azusa) // -> { ... { handle: '@nakano' } ... }

You can find similar example code in /test.

API

lens.ts exports the followings:

import {
  lens,
  Getter,
  Setter,
  Lens
} from 'lens.ts';

lens

A function lens is a factory function for a lens. Without any arguments except for a type parameter, it returns an identity lens for the provided type.

lens<Person>() // :: Lens<Person, Person>

You can provide a getter and a setter to create a lens manually. They should have proper Getter and Setter types.

let getter // :: Getter<X, Y>
let setter // :: (val: Y) => Setter<X>
lens(getter, setter) // :: Lens<X, Y>

Getter, Setter

They are just a type alias for the following function types.

export type Getter<T, V> = (target: T) => V;
export type Setter<T>    = (target: T) => T;

Basically, Getter is a function to retrieve a value from a target. Setter is a function to set or update a value in a provided target and return a new object with a same type as the target.

Any Setter returned from Lens has immutable API, which means it doesn't modify the target object.

Lens<T, U>

A lens is consisted of a getter and a setter for a source type T and a result type U.

Lens is not a class, so it can't be created with new Lens(). It's internally a product type of LensImpl and LensProxy. Please use lens() to create a lens.

Lens provides the following methods.

.k<K extends keyof U>(key: K)

Narrow the lens for a property or an index of U.

// we will use these types for the following examples
type Person = {
  name: string;
  age: number;
  accounts: Account[];
};

lens<Person>().k('name') // :: Lens<Person, string>
lens<Person>().k('accounts') // :: Lens<Person, Account[]>
lens<Person>().k('accounts').k(0) // :: Lens<Person, Account>

.get()

It is polymorphic.

  • .get(): Getter<T, U>
  • .get<V>(f: Getter<U, V>): Getter<T, V>

.get() returns a getter, which can be applied to an actual target object to retrive an actual value. You can optionally provide another getter (or mapping function) to retrieve a mapped value.

let target = { age: 15, ... };

let ageL = lens<Person>().k('age');

ageL.get()(target) // -> 15
ageL.get(age => age + 10)(target) // -> 25

.set()

It is polymorphic.

  • .set(val: U): Setter<T>
  • .set(f: Setter<U>): Setter<T>

.set() returns a setter, which can set or update an internal value and returns an updated (and new) object. Setters here should be all immutable. You can provide a value to set, or optionally a setter for value.

let target = { age: 15, ... };

let ageL = lens<Person>().k('age');

ageL.set(20)(target) // -> { age: 20, ... }
ageL.set(age => age + 1)(target) // -> { age: 16, ... }

.compose(another: Lens<U, V>): Lens<U, V>

Compose 2 lenses into one.

let lens1: Lens<T, U>;
let lens2: Lens<U, V>;

let accountsL = lens<Person>().k('accounts');
let firstL = <T>() => lens<T[]>().k(0);

let firstAccountL =
  accountsL.compose(firstL()); // :: Lens<Person, Account>

FYI: The reason firstL becomes a function with <T> is to make it polymorphic.

Proxied properties

Lens<T, U> also provides proxied properties for the type U.

objL.name // same as objL.k('name')
arrL[0] // same as arrL.k(0)

Note that proxy objects are not available in Internet Explorer as caniuse describes.

Credits

Property proxy couldn't have been implemented without @ktsn's help.

License

MIT

More Repositories

1

kawa

A macOS input source switcher with user-defined shortcuts.
Swift
1,369
star
2

pen

We need a better Markdown previewer.
JavaScript
326
star
3

react-render-html

Render HTML as React element, possibly replacing dangerouslySetInnerHTML
JavaScript
216
star
4

kou

A minimal language compiled into wasm bytecode
TypeScript
134
star
5

express-formidable

An Express middleware of Formidable that just works.
JavaScript
132
star
6

tinypack

A simple TypeScript module bundler
TypeScript
63
star
7

monkey-hs

An interpreter for the Monkey programming language written in Haskell
Haskell
49
star
8

incinerator

A PoC implementation of unused code elimination in runtime
JavaScript
43
star
9

monkey-rs

An interpreter for the Monkey programming language written in Rust
Rust
37
star
10

line

Haskell SDK for the LINE APIs
Haskell
31
star
11

ClassHierarchy

Class Hierarchy with CTags for Sublime Text 2
Python
20
star
12

uit-meetup-11

UIT meetup vol.11 talk: Build you a static site generator
JavaScript
13
star
13

futaba

TensorFlow.js Example for Color Personalization
Vue
12
star
14

s-exify

Beautifier for S-expression, mainly for WAT
TypeScript
11
star
15

react-attr-converter

Convert HTML attribute names to React props
JavaScript
8
star
16

purescript-halogen-free-html

Free monad for Halogen HTML
PureScript
8
star
17

dotfiles

dotfiles for me
Vim Script
8
star
18

osx-screen-capture

Screen capture and upload tool for OS X.
Python
4
star
19

coursera-machine-learning

Programming assignments of the Machine Learning course in Coursera
MATLAB
4
star
20

mitty

A Brain*uck to WASM compiler
Brainfuck
4
star
21

suzu

SimpleHTTPServer alternative for Node.js, with no cache
JavaScript
3
star
22

MACwMP

Monadic array comprehension with meta programming in JS
JavaScript
3
star
23

smi-editor

Command-line SMI editor script only for synchronizing the subtitle!
Python
2
star
24

previewable-iterator

Previewable Iterable/Iterator for JavaScript/TypeScript
TypeScript
2
star
25

lint-webpack-plugin

A webpack plugin to run custom lint shell command
JavaScript
2
star
26

touhou-css

A CSS practice with Touhou
CSS
2
star
27

evernote2bitly

import evernote enex file format bookmarks into bitly
Python
1
star
28

bookmark

A simple bookmark script for me and you.
1
star
29

safari-imgur

DIY Safari Extension to upload images to Imgur
JavaScript
1
star
30

shogi-ui

A collection of HTML, CSS and JS for Shogi (将棋) UI on Web.
JavaScript
1
star
31

chess

A chess server
Go
1
star
32

scenic

See great pictures with your friends!
JavaScript
1
star
33

game-of-life

Conway's Game of Life with CoffeeScript
CoffeeScript
1
star
34

mahjong-statistics

django powered mahjong statistics
Python
1
star
35

euler

A Haskell adventure into Project Euler
Haskell
1
star
36

typed-styled-components

TypeScript + styled-components in a simple way
TypeScript
1
star
37

soramaru

A Twitter list viewer for images
JavaScript
1
star