0.3.0 • Published 5 years ago

mch v0.3.0

Weekly downloads
133
License
MIT
Repository
github
Last release
5 years ago

mch

A fun library emulating (some of) the upcoming pattern matching proposal.

No dependencies and native TypeScript support.

Supports a variety of match types:

TypeExamplesMatch method
Valuewhen(20, ...)Strictly equals the exact value
Objectwhen({ status: Number }, ...)Recursively passes each key condition
Constructorwhen(String, ...)Instance of the constructor
RegExpwhen(/hi/, ...)Tests positive against the RegExp
Compare Functionwhen(x => x === 10, ...)Custom compare function
Defaultotherwise(...)Default fallback that maches anything

Install

npm install mch or yarn add mch

Usage

import { match, otherwise, when } from "mch"

Example usage returning a phrase based on a number.

const message = match(count, [
  when(0, () => "None for you"),
  when(1, () => "You have one"),
  when(Number, x => `You have ${x}`),
  otherwise(() => {
    throw new Error("Is this even a number?") // it's not
  }),
])

Example usage with React.

<div>
  {match(value, [
    when(0, () => <span>You have none</span>),
    when(Number, x => <span>You have {x}</span>),
    when(Error, error => <ErrorRender error={error}>),
  ])}
</div>

Example usage with async/await and a fetch response.

const response = await fetch(url)

const body = await match(response, [
  when({ status: /2\d\d/ }, res => res.json()),
  when({ status: 404 }, () => {
    throw new Error("404 Not Found")
  }),
])

Example usage the spirit of Rust's result convention.

function findValue(x: number): Result<number, string> {
  return x > 0 ? new Ok(x) : new Err("Invalid number")
}

const result = match(findValue(number), [
  when(Ok, ({ value }) => value),
  when(Err, () => 0),
])
0.3.0

5 years ago

0.2.0

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago