Headpats

Pattern matching and tagged unions in JavaScript without new syntax.
See the guide on how to use Headpats! Refer to the documentation for specific information on pattern matching and built-in features.

Examples

Setup

const pat = require('headpats');
const { $, $$, _, is, rest } = pat;

Stringly Typed

function doOperation(operation, a, b) {
    return pat
        .case('add', () => a + b)
        .case('minus', () => a - b)
        .case(_, () => NaN)(operation);
}

doOperation('add', 1, 2)
ā†’ 3

doOperation('minus', 1, 2)
ā†’ -1

doOperation('something', 1, 2)
ā†’ NaN

Safe Traversal

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

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

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

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]

Headpats

Pattern matching and tagged unions in JavaScript without new syntax.

Headpats Info

ā­ Stars 14
šŸ”— Source Code github.com
šŸ•’ Last Update 2 years ago
šŸ•’ Created 3 years ago
šŸž Open Issues 0
āž— Star-Issue Ratio Infinity
šŸ˜Ž Author 1Computer1