A basic JavaScript version of Rust pattern matching.
pnpm install @citrus327/match --save
or using deno
deno add @citrus327/match
check out tests for more examples.
import { match, _ } from '@citrus327/match';
function t1 () {
const a = "hello"
const result = match(a, [
["hello", () => 1],
["world", () => 2],
[_, () => undefined],
])
console.log(result === 1) // true
}
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
}
- 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.
- 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