Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standalone (floating) optics #155

Merged
merged 30 commits into from
Aug 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ node_modules
dist
dist-test
.idea
*.d.ts
venv
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
dist/
venv/
package.json
162 changes: 162 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,165 @@
`optics-ts` supports lenses, prisms, traversals, removing items from containers,
and much more! See the [documentation](https://akheron.github.io/optics-ts) for
a tutorial and a detailed reference of all supported optics.

There are currently two "syntaxes" for defining optics: method chaining and
standalone optics. Method chaining is still the default syntax and standalone
syntax is considered experimental, but will probably become the default in the
future.

Here's a standalone optics example, demonstrating how to drill in to a nested
data structure:

```typescript
// Import the standalone library
import * as O from 'optics-ts/floating'

// Create a lens that focuses on author.name. Plain strings works like O.prop().
const optic = O.compose('author', 'name')

// This is the input data
const input = {
title: "The Hitchhiker's Guide to the Galaxy"
isbn: "978-0345391803",
author: {
name: "Douglas Adams"
}
}

// Read through the optic
O.get(optic, input)
// "Douglas Adams"

// Write through the optic
O.set(optic, "Arthur Dent", input)
// {
// title: "The Hitchhiker’s Guide to the Galaxy"
// isbn: "978-0345391803",
// author: {
// name: "Arthur Dent"
// }
// }

// Update the existing value through the optic, while also changing the data type
O.modify(optic, str => str.length + 29, input)
// {
// title: "The Hitchhiker’s Guide to the Galaxy"
// isbn: "978-0345391803",
// author: {
// name: 42
// }
// }
```

Here's the same example with optics defined by method chaining:

```typescript
// Importing from the top-level gives method chaining optics
import * as O from 'optics-ts'

type Book = {
title: string
isbn: string
author: {
name: string
}
}

// Create a lens that focuses on author.name
const optic = O.optic_<Book>()
.prop('author')
.prop('name')

// This is the input data
const input: Book = {
title: "The Hitchhiker's Guide to the Galaxy"
isbn: "978-0345391803",
author: {
name: "Douglas Adams"
}
}

// Read through the optic
O.get(optic)(input)
// "Douglas Adams"

// Write through the optic
O.set(optic)("Arthur Dent")(input)
// {
// title: "The Hitchhiker’s Guide to the Galaxy"
// isbn: "978-0345391803",
// author: {
// name: "Arthur Dent"
// }
// }

// Update the existing value through the optic, while also changing the data type
O.modify(optic)(str => str.length + 29)(input)
// {
// title: "The Hitchhiker’s Guide to the Galaxy"
// isbn: "978-0345391803",
// author: {
// name: 42
// }
// }
```

Another example with standalone optics that converts all words longer than 5
characters to upper case:

```typescript
import * as O from 'optics-ts/floating'

const optic = O.compose(
O.words,
O.when((s: string) => s.length >= 5)
)

const input = 'This is a string with some shorter and some longer words'
O.modify(optic, (s) => s.toUpperCase(), input)
// "This is a STRING with some SHORTER and some LONGER WORDS"
```

## Development

Run `yarn` to install dependencies.

### Running the test suite

Run `yarn test`.

For compiling and running the tests when files change, run these commands in
separate terminals:

```
yarn build:test --watch
yarn jest dist-test/ --watchAll
```

### Documentation

You need Python 3 to build the docs.

```
python3 -m venv venv
./venv/bin/pip install mkdocs-material
```

Run a live reloading server for the documentation:

```
./venv/bin/mkdocs serve
```

Open http://localhost:8000/ in the browser.

### Releasing

```
$ yarn version --new-version <major|minor|patch>
$ yarn publish
$ git push origin main --tags
```

Open https://github.com/akheron/optics-ts/releases, edit the draft release,
select the newest version tag, adjust the description as needed.
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
testEnvironment: 'node',
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
roots: ['dist-test/'],
};
27 changes: 20 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,30 @@
"immutable",
"functional-programming"
],
"main": "./dist/lib/index.js",
"module": "./dist/esm/index.js",
"typings": "./dist/lib/index.d.ts",
"exports": {
".": {
"import": "./dist/mjs/index.js",
"require": "./dist/cjs/index.js"
},
"./floating": {
"import": "./dist/mjs/floating/index.js",
"require": "./dist/cjs/floating/index.js"
}
},
"files": [
"dist"
"dist",
"floating",
"*.d.ts"
],
"scripts": {
"build": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.esm.json",
"typecheck": "tsc --noEmit",
"build": "yarn build:cjs && yarn build:mjs && yarn build:typings && scripts/fixup",
"build:cjs": "tsc -p tsconfig.cjs.json",
"build:mjs": "tsc -p tsconfig.mjs.json",
"build:typings": "tsc -p tsconfig.typings.json",
"build:test": "tsc -p tsconfig.test.json",
"test": "yarn build:test && jest dist-test/",
"clean": "rm -rf dist/ dist-test/",
"test": "yarn build:test && jest",
"clean": "rm -rf dist/ dist-test/ floating/ *.d.ts",
"lint": "eslint --max-warnings 0 '**/*.ts' && prettier --check \"**/*.{json,md}\"",
"lint:fix": "eslint --fix '**/*.ts' && prettier --write '**/*.{json,md}'",
"prepublishOnly": "yarn run clean && yarn run build",
Expand Down
14 changes: 14 additions & 0 deletions scripts/fixup
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/sh
set -e

cat >dist/cjs/package.json <<EOF
{
"type": "commonjs"
}
EOF

cat >dist/mjs/package.json <<EOF
{
"type": "module"
}
EOF
6 changes: 3 additions & 3 deletions scripts/generate-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const header = `\
/* eslint-disable @typescript-eslint/no-non-null-assertion, @typescript-eslint/adjacent-overload-signatures, @typescript-eslint/no-unused-vars, @typescript-eslint/ban-types */
// This file is generated, do not edit! See ../scripts/generate-index.ts

import * as I from './internals'
import * as I from './internals.js'
import {
ElemType,
Eq,
Expand All @@ -14,7 +14,7 @@ import {
TuplePath,
RequireString,
Simplify
} from './utils'
} from './utils.js'
import {
Adapt,
Apply,
Expand All @@ -34,7 +34,7 @@ import {
SetDottedPath,
SetTuplePath,
Union,
} from './hkt'
} from './hkt.js'

export { Apply, Compose, Eq, HKT }

Expand Down
17 changes: 17 additions & 0 deletions src/floating/appendTo.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as O from '.'

describe('appendTo', () => {
type Source = string[]
const source = ['foo', 'bar']

it('set - monomorphic', () => {
const result1: Source = O.set(O.appendTo, 'abc', source)
expect(result1).toEqual(['foo', 'bar', 'abc'])
})

type Target = (string | number)[]
it('set - polymorphic', () => {
const result1: Target = O.set(O.appendTo, 42, source)
expect(result1).toEqual(['foo', 'bar', 42])
})
})
14 changes: 14 additions & 0 deletions src/floating/appendTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Optic, TryT, B, S, T } from './optic.js'
import * as I from '../internals.js'
import type { ArrayExpected } from './errors.js'

interface AppendToT extends T {
0: TryT<
this,
S<this> extends (infer Item)[] ? (Item | B<this>)[] : ArrayExpected<S<this>>
>
}

export type AppendTo = Optic<'Setter', never, AppendToT>

export const appendTo: AppendTo = I.appendTo as any
10 changes: 10 additions & 0 deletions src/floating/appendTo.tspec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { expectType } from './test-utils.tspec.js'
import * as O from '.'
import type { ArrayExpected } from './errors.js'

describe('appendTo', () => {
it('set - source not an array', () => {
const result = O.set(O.appendTo, 'foo', 3)
expectType<ArrayExpected<number>>()(result)()
})
})
93 changes: 93 additions & 0 deletions src/floating/at.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import * as O from '.'

describe('at (on array)', () => {
type Source = string[]
const source1: Source = ['foo', 'bar', 'baz', 'quux']
const source2: Source = ['foo']

const prism = O.at(1)
type Focus = string | undefined

it('preview defined', () => {
const result: Focus = O.preview(prism, source1)
expect(result).toEqual('bar')
})
it('preview undefined', () => {
const result: Focus = O.preview(prism, source2)
expect(result).toBeUndefined()
})

it('set defined - monomorphic', () => {
const result: Source = O.set(prism, 'UPDATED', source1)
expect(result).toEqual(['foo', 'UPDATED', 'baz', 'quux'])
})
it('set undefined - monomorphic', () => {
const result: Source = O.set(prism, 'UPDATED', source2)
expect(result).toEqual(source2)
})
it('modify defined - monomorphic', () => {
const result: Source = O.modify(prism, (x) => `${x} UPDATED`, source1)
expect(result).toEqual(['foo', 'bar UPDATED', 'baz', 'quux'])
})
it('modify undefined - monomorphic', () => {
const result: Source = O.modify(prism, (x) => `${x} UPDATED`, source2)
expect(result).toEqual(source2)
})

type Target = Array<string | number>
it('modify defined - polymorphic', () => {
const result: Target = O.modify(prism, (x) => x.length, source1)
expect(result).toEqual(['foo', 3, 'baz', 'quux'])
})
it('modify undefined - polymorphic', () => {
const result: Target = O.modify(prism, (x) => x.length, source2)
expect(result).toEqual(source2)
})

it('remove defined', () => {
const result: Source = O.remove(prism, source1)
expect(result).toEqual(['foo', 'baz', 'quux'])
})

it('remove undefined', () => {
const result: Source = O.remove(prism, source2)
expect(result).toEqual(['foo'])
})
})

describe('at (on string)', () => {
type Source = string
const source1: Source = 'foobarbaz'
const source2: Source = 'foo'

const prism = O.at(3)
type Focus = string | undefined

it('preview defined', () => {
const result: Focus = O.preview(prism, source1)
expect(result).toEqual('b')
})
it('preview undefined', () => {
const result: Focus = O.preview(prism, source2)
expect(result).toBeUndefined()
})

it('set defined - monomorphic', () => {
const result: Source = O.set(prism, 'UPDATED', source1)
expect(result).toEqual('fooUPDATEDarbaz')
})
it('set undefined - monomorphic', () => {
const result: Source = O.set(prism, 'UPDATED', source2)
expect(result).toEqual(source2)
})

it('remove defined', () => {
const result: Source = O.remove(prism, source1)
expect(result).toEqual('fooarbaz')
})

it('remove undefined', () => {
const result: Source = O.remove(prism, source2)
expect(result).toEqual('foo')
})
})
Loading