mch
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

mch

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

No dependencies and native TypeScript support.

Supports a variety of match types:

Type Examples Match method
Value when(20, ...) Strictly equals the exact value
Object when({ status: Number }, ...) Recursively passes each key condition
Constructor when(String, ...) Instance of the constructor
RegExp when(/hi/, ...) Tests positive against the RegExp
Compare Function when(x => x === 10, ...) Custom compare function
Default otherwise(...) 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),
])

Readme

Keywords

none

Package Sidebar

Install

npm i mch

Weekly Downloads

3

Version

0.3.0

License

MIT

Unpacked Size

10.6 kB

Total Files

14

Last publish

Collaborators

  • joelshepherd