@citrus327/match
v1.0.0
Published
My awesome typescript library
Downloads
1
Readme
match
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
- if multiple matchers found,
match
will only match the first one (same as fallback matchers). - 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