• Stars
    star
    1,001
  • Rank 44,020 (Top 0.9 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Functional optics: a (partial) porting of Scala monocle

build status dependency status npm downloads

Motivation

(Adapted from monocle site)

Modifying immutable nested object in JavaScript is verbose which makes code difficult to understand and reason about.

Let's have a look at some examples:

interface Street {
  num: number
  name: string
}
interface Address {
  city: string
  street: Street
}
interface Company {
  name: string
  address: Address
}
interface Employee {
  name: string
  company: Company
}

Let’s say we have an employee and we need to upper case the first character of his company street name. Here is how we could write it in vanilla JavaScript

const employee: Employee = {
  name: 'john',
  company: {
    name: 'awesome inc',
    address: {
      city: 'london',
      street: {
        num: 23,
        name: 'high street'
      }
    }
  }
}

const capitalize = (s: string): string => s.substring(0, 1).toUpperCase() + s.substring(1)

const employeeCapitalized = {
  ...employee,
  company: {
    ...employee.company,
    address: {
      ...employee.company.address,
      street: {
        ...employee.company.address.street,
        name: capitalize(employee.company.address.street.name)
      }
    }
  }
}

As we can see copy is not convenient to update nested objects because we need to repeat ourselves. Let's see what could we do with monocle-ts

import { Lens } from 'monocle-ts'

const company = Lens.fromProp<Employee>()('company')
const address = Lens.fromProp<Company>()('address')
const street = Lens.fromProp<Address>()('street')
const name = Lens.fromProp<Street>()('name')

compose takes two Lenses, one from A to B and another one from B to C and creates a third Lens from A to C. Therefore, after composing company, address, street and name, we obtain a Lens from Employee to string (the street name). Now we can use this Lens issued from the composition to modify the street name using the function capitalize

const capitalizeName = company.compose(address).compose(street).compose(name).modify(capitalize)

assert.deepStrictEqual(capitalizeName(employee), employeeCapitalized)

You can use the fromPath API to avoid some boilerplate

import { Lens } from 'monocle-ts'

const name = Lens.fromPath<Employee>()(['company', 'address', 'street', 'name'])

const capitalizeName = name.modify(capitalize)

assert.deepStrictEqual(capitalizeName(employee), employeeCapitalized) // true

Here modify lift a function string => string to a function Employee => Employee. It works but it would be clearer if we could zoom into the first character of a string with a Lens. However, we cannot write such a Lens because Lenses require the field they are directed at to be mandatory. In our case the first character of a string is optional as a string can be empty. So we need another abstraction that would be a sort of partial Lens, in monocle-ts it is called an Optional.

import { Optional } from 'monocle-ts'
import { some, none } from 'fp-ts/Option'

const firstLetterOptional = new Optional<string, string>(
  (s) => (s.length > 0 ? some(s[0]) : none),
  (a) => (s) => (s.length > 0 ? a + s.substring(1) : s)
)

const firstLetter = company.compose(address).compose(street).compose(name).asOptional().compose(firstLetterOptional)

assert.deepStrictEqual(firstLetter.modify((s) => s.toUpperCase())(employee), employeeCapitalized)

Similarly to compose for lenses, compose for optionals takes two Optionals, one from A to B and another from B to C and creates a third Optional from A to C. All Lenses can be seen as Optionals where the optional element to zoom into is always present, hence composing an Optional and a Lens always produces an Optional.

TypeScript compatibility

The stable version is tested against TypeScript 3.5.2, but should run with TypeScript 2.8.0+ too

monocle-ts version required typescript version
2.0.x+ 3.5+
1.x+ 2.8.0+

Note. If you are running < [email protected] you have to polyfill unknown.

You can use unknown-ts as a polyfill.

Documentation

Experimental modules (version 2.3+)

Experimental modules (*) are published in order to get early feedback from the community.

The experimental modules are independent and backward-incompatible with stable ones.

(*) A feature tagged as Experimental is in a high state of flux, you're at risk of it changing without notice.

From [email protected]+ you can use the following experimental modules:

  • Iso
  • Lens
  • Prism
  • Optional
  • Traversal
  • At
  • Ix

which implement the same features contained in index.ts but are pipe-based instead of class-based.

Here's the same examples with the new API

interface Street {
  num: number
  name: string
}
interface Address {
  city: string
  street: Street
}
interface Company {
  name: string
  address: Address
}
interface Employee {
  name: string
  company: Company
}

const employee: Employee = {
  name: 'john',
  company: {
    name: 'awesome inc',
    address: {
      city: 'london',
      street: {
        num: 23,
        name: 'high street'
      }
    }
  }
}

const capitalize = (s: string): string => s.substring(0, 1).toUpperCase() + s.substring(1)

const employeeCapitalized = {
  ...employee,
  company: {
    ...employee.company,
    address: {
      ...employee.company.address,
      street: {
        ...employee.company.address.street,
        name: capitalize(employee.company.address.street.name)
      }
    }
  }
}

import * as assert from 'assert'
import * as L from 'monocle-ts/Lens'
import { pipe } from 'fp-ts/function'

const capitalizeName = pipe(
  L.id<Employee>(),
  L.prop('company'),
  L.prop('address'),
  L.prop('street'),
  L.prop('name'),
  L.modify(capitalize)
)

assert.deepStrictEqual(capitalizeName(employee), employeeCapitalized)

import * as O from 'monocle-ts/Optional'
import { some, none } from 'fp-ts/Option'

const firstLetterOptional: O.Optional<string, string> = {
  getOption: (s) => (s.length > 0 ? some(s[0]) : none),
  set: (a) => (s) => (s.length > 0 ? a + s.substring(1) : s)
}

const firstLetter = pipe(
  L.id<Employee>(),
  L.prop('company'),
  L.prop('address'),
  L.prop('street'),
  L.prop('name'),
  L.composeOptional(firstLetterOptional)
)

assert.deepStrictEqual(
  pipe(
    firstLetter,
    O.modify((s) => s.toUpperCase())
  )(employee),
  employeeCapitalized
)

More Repositories

1

fp-ts

Functional programming in TypeScript
TypeScript
10,469
star
2

io-ts

Runtime type system for IO decoding/encoding
TypeScript
6,598
star
3

tcomb-form-native

Forms library for react-native
JavaScript
3,153
star
4

tcomb

Type checking and DDD for JavaScript
JavaScript
1,897
star
5

tcomb-form

Forms library for react
JavaScript
1,163
star
6

newtype-ts

Implementation of newtypes in TypeScript
TypeScript
553
star
7

babel-plugin-tcomb

Babel plugin for static and runtime type checking using Flow and tcomb
JavaScript
483
star
8

flow-static-land

[DEPRECATED, please check out fp-ts] Implementation of common algebraic types in JavaScript + Flow
JavaScript
408
star
9

functional-programming

Introduction to Functional Programming (Italian)
TypeScript
401
star
10

tcomb-validation

Validation library based on type combinators
JavaScript
400
star
11

typelevel-ts

Type level programming in TypeScript
TypeScript
354
star
12

io-ts-types

A collection of codecs and combinators for use with io-ts
TypeScript
309
star
13

elm-ts

A porting to TypeScript featuring fp-ts, rxjs6 and React
TypeScript
301
star
14

redux-tcomb

Immutable and type-checked state and actions for Redux
JavaScript
211
star
15

tcomb-react

Alternative syntax for PropTypes
JavaScript
202
star
16

fp-ts-contrib

A community driven utility package for fp-ts
TypeScript
198
star
17

parser-ts

String parser combinators for TypeScript
TypeScript
190
star
18

fp-ts-rxjs

fp-ts bindings for RxJS
TypeScript
187
star
19

prop-types-ts

Alternative syntax for prop types providing both static and runtime type safety, powered by io-ts
TypeScript
170
star
20

fp-ts-routing

A type-safe bidirectional routing library for TypeScript
TypeScript
167
star
21

retry-ts

Retry combinators for monadic actions that may fail
TypeScript
162
star
22

io-ts-codegen

Code generation for io-ts
TypeScript
152
star
23

tcomb-json-schema

Transforms a JSON Schema to a tcomb type
JavaScript
144
star
24

flowcheck

[DEPRECATED, use babel-plugin-tcomb instead] Runtime type checking for Flow
JavaScript
116
star
25

fp-ts-codegen

TypeScript code generation from a haskell-like syntax for ADT. Playground:
TypeScript
101
star
26

logging-ts

Composable loggers for TypeScript
TypeScript
99
star
27

docs-ts

A zero-config documentation tool for my TypeScript projects
TypeScript
94
star
28

flowcheck-loader

[DEPRECATED] A Webpack loader for Flowcheck
JavaScript
89
star
29

tom

Elmish type-safe state and side effect manager using RxJS
JavaScript
87
star
30

money-ts

TypeScript library for type-safe and lossless encoding and manipulation of world currencies and precious metals
TypeScript
87
star
31

fp-ts-laws

fp-ts type class laws for property based testing
TypeScript
80
star
32

flow-io

[DEPRECATED, please check out io-ts] Flow compatible runtime type system for IO validation
JavaScript
73
star
33

react-vdom

Pulls out the VDOM and makes tests easy (also in node and without the DOM)
JavaScript
72
star
34

uvdom

Universal Virtual DOM
JavaScript
53
star
35

fp-ts-fluture

fp-ts bindings for Fluture
TypeScript
50
star
36

fp-ts-local-storage

fp-ts bindings for LocalStorage
TypeScript
49
star
37

graphics-ts

A porting of purescript-{canvas, drawing} featuring fp-ts
TypeScript
44
star
38

tcomb-react-bootstrap

Type checking for react-bootstrap [DEPRECATED]
JavaScript
41
star
39

talks

talks and blog posts
HTML
41
star
40

unknown-ts

A polyfill of unknown that works with legacy typescript versions (before 3.0)
TypeScript
28
star
41

mtl-ts

MTL-style in TypeScript
TypeScript
24
star
42

recursion-schemes-ts

Recursion schemes in TypeScript (POC)
TypeScript
22
star
43

tcomb-doc

Documentation tool for tcomb
JavaScript
14
star
44

babel-plugin-tcomb-boilerplate

Boilerplate showing what you can get in terms of type safety with babel-plugin-tcomb
JavaScript
14
star
45

fp-ts-node

TypeScript
13
star
46

flow-react

Advanced type checking for react using Flow
JavaScript
13
star
47

pantarei

Repository for idiomatic Flowtype definition files
JavaScript
11
star
48

elm-ts-todomvc

todomvc implementation using elm-ts and fp-ts
TypeScript
11
star
49

typescript-course

Esercizi del corso di programmazione avanzata con TypeScript
TeX
11
star
50

tcomb-form-templates-semantic

Semantic UI templates for tcomb-form
JavaScript
11
star
51

tcomb-form-templates-bootstrap

Bootstrap templates for tcomb-form
JavaScript
10
star
52

sanctuary-libdef

Flow definition file for sanctuary
JavaScript
9
star
53

simple-date-picker

A simple clean way to pick dates with React
JavaScript
9
star
54

flow-update

Statically type checked model updates using Flow
JavaScript
8
star
55

profunctor-lenses-ts

Pure profunctor lenses in TypeScript (just a POC)
TypeScript
8
star
56

fp-typed-install

TypeScript
7
star
57

cerebral-tcomb

[No Maintenance Intended] immutable and type checked model layer for cerebral
JavaScript
7
star
58

import-path-rewrite

JavaScript
6
star
59

fractal-trees-ts

Fractal trees with fp-ts
TypeScript
6
star
60

fcomb

Function combinators
JavaScript
5
star
61

uvdom-bootstrap

Bootstrap 3 components built with uvdom
JavaScript
5
star
62

simple-format-number

A simple clean way to format numbers with Javascript
JavaScript
5
star
63

behaviors-ts

A porting of purescript-behaviors
TypeScript
5
star
64

tree-shaking-test

JavaScript
4
star
65

io-ts-benchmarks

TypeScript
3
star
66

fetch-optimizer

[No Maintenance Intended] Optimises dependent data fetchers
JavaScript
2
star
67

simple-format-timeago

A simple clean way to format intervals with Javascript
JavaScript
2
star
68

tcomb-i18n

Simple i18n / i17n helpers [DEPRECATED]
JavaScript
2
star
69

simple-format-date

A simple clean way to format dates with Javascript
JavaScript
2
star
70

simple-parse-number

A simple clean way to parse numbers with Javascript
JavaScript
1
star