https://github.com/1computer1/headpats
Pattern matching and tagged unions in JavaScript without new syntax.
https://github.com/1computer1/headpats
case clauses discriminated-unions matching pattern pattern-matching patterns tagged-unions
Last synced: about 1 month ago
JSON representation
Pattern matching and tagged unions in JavaScript without new syntax.
- Host: GitHub
- URL: https://github.com/1computer1/headpats
- Owner: 1Computer1
- License: mit
- Created: 2018-08-24T23:38:27.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2018-09-08T16:58:18.000Z (over 6 years ago)
- Last Synced: 2025-03-25T02:43:53.768Z (about 2 months ago)
- Topics: case, clauses, discriminated-unions, matching, pattern, pattern-matching, patterns, tagged-unions
- Language: JavaScript
- Homepage:
- Size: 112 KB
- Stars: 13
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Headpats
Pattern matching and tagged unions in JavaScript without new syntax.
See the [guide](./docs/0.%20How%20to%20Use.md) on how to use Headpats!
Refer to the [documentation](./docs) for specific information on pattern matching and built-in features.## Examples
**Setup**
```js
const pat = require('headpats');
const { $, $$, _, is, rest } = pat;
```**Stringly Typed**
```js
function doOperation(operation, a, b) {
return pat
.case('add', () => a + b)
.case('minus', () => a - b)
.case(_, () => NaN)(operation);
}doOperation('add', 1, 2)
→ 3doOperation('minus', 1, 2)
→ -1doOperation('something', 1, 2)
→ NaN
```**Safe Traversal**
```js
const o = { x: { y: { z: 10 } } };pat.match({ x: { y: { z: $.z } } }, o)
→ { z: 10 }pat.match({ x: { y: { what: $.what } } }, o)
→ null
```**Result Matching**
```js
const ok = Symbol('ok');
const err = Symbol('err');function divide(a, b) {
if (b === 0) {
return [err, null];
}return [ok, a / b];
}pat.match([ok, $.num], divide(10, 2));
→ { num: 5 }
```**Option Type**
```js
const Option = pat.union('Option', 'Some', 'None');
const { Some, None } = Option;const double = pat
.case($$(Some, $.x), ({ x }) => new Some(x * 2))
.case($$(None, _), () => new None());double(new Some(5))
→ Some { x: 10 }double(new None())
→ None {}double(100)
→ Error
```**Recursive Map**
```js
const map = pat
.clause([], _, () => [])
.clause([$.x, [rest, $.xs]], $.f, ({ x, xs, f }) => [f(x)].concat(map(xs, f)));map([1, 2, 3, 4], x => x * 2)
→ [2, 4, 6, 8]
```