Skip to content

A JavaScript version of Rust pattern matching.

License

Notifications You must be signed in to change notification settings

citrus327/match

Repository files navigation

match

Download Version

A basic JavaScript version of Rust pattern matching.

Installation

pnpm install @citrus327/match --save

or using deno

deno add @citrus327/match

Usage

check out tests for more examples.

Basic

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

function t1 () {
  const a = "hello"
  const result = match(a, [
    ["hello", () => 1],
    ["world", () => 2],
    [_, () => undefined],
  ])
  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"],
    [_, () => undefined],
  ])
  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],
    [_, () => undefined],
  ])

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

About

A JavaScript version of Rust pattern matching.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published