Skip to main content

latest
Works with
JSR Score
52%
Published
2 months ago (1.0.0)

match

Download Version

A basic JavaScript version of Rust pattern matching.

Installation

pnpm install @citrus327/match --save

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

Add Package

deno add @citrus327/match

Import symbol

import * as mod from "@citrus327/match";

Add Package

npx jsr add @citrus327/match

Import symbol

import * as mod from "@citrus327/match";

Add Package

yarn dlx jsr add @citrus327/match

Import symbol

import * as mod from "@citrus327/match";

Add Package

pnpm dlx jsr add @citrus327/match

Import symbol

import * as mod from "@citrus327/match";

Add Package

bunx jsr add @citrus327/match

Import symbol

import * as mod from "@citrus327/match";