@citrus327/match
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

match

Download Version

A basic JavaScript version of Rust pattern matching.

Installation

pnpm install @citrus327/match --save

Usage

checkout tests for more examples.

Basic

import { match, _ } from '@citrus327/match';

function t1 () {
  const a = "hello"
  const result = match(a, [
    ["hello", () => 1],
    ["world", () => 2],
    [_, () => null],
  ])
  console.log(result === 1) // true
}

with Typescript Enum

import { match, _ } from '@citrus327/match';

function t1 () {
  enum Flag {
    Yes = 1,
    No = 2,
  }
  const flag = Flag.Yes
  const result = match(flag, [
    [Flag.Yes, () => "YES"],
    [Flag.No, () => "NO"],
  ])
  console.log(result === "YES") // true
}

Rules

  1. if multiple matchers found, match will only match the first one (same as fallback matchers).
  2. must contain a fallback matcher, match will throw if no fallback matcher found.

These two rules are followed by Rust's implementation.

Comparison

  • In Rust
fn main() {
  let number = 1;
  match number {
      1 => println!("One!"),
      _ => println!("Ain't special"),
  }

  let boolean = true;
  let binary = match boolean {
      false => 0,
      true => 1,
  };

  println!("{} -> {}", boolean, binary);
}
// output: 
// One!
// true -> 1
  • In Javascript
import { match, _ } from '@citrus327/match';

function main () {
  let number = 1;
  match(number, [
    [1, () => console.log("One!")],
    [_, () => console.log("Ain't special")]
  ])

  let boolean = true;
  let binary = match(boolean, [
    [false, () => 0],
    [true, () => 1],
  ])

  console.log(`${boolean} -> ${binary}`);
}
// output: 
// One!
// true -> 1

Readme

Keywords

none

Package Sidebar

Install

npm i @citrus327/match

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

7.09 kB

Total Files

7

Last publish

Collaborators

  • hophop0327