Simple and lightweight library for handling switch statements and Pattern Matching in JavaScript and TypeScript.
To install the package, you can use npm or your favorite package manager.
npm install switch-matcher
- Simple: Uses a syntax similar to JavaScript switch statements and chainable methods.
- Lightweight: Has few dependencies and is very lightweight.
- Versatile: Can be used in any JavaScript or TypeScript project.
Switch-Matcher
provides two main interfaces to work with: the Switcher
and Matcher
classes (the latter through the match
function).
Here comes a more detailed description of the interfaces.
SMSwitcher
is a class that facilitates the definition and evaluation of conditions in a structured manner. It allows creating a pipeline through multiple cases (case
), a default handler (default
), and an alternative handler (else
). Additionally, it supports both synchronous and asynchronous evaluations.
First, import the SMSwitcher
class.
import { SMSwitcher } from "switch-matcher";
const switcher = new SMSwitcher<string, string>();
switcher
.case("value1", () => "Handled value1")
.case("value2", "Handled value2")
.case((value) => value.startsWith("test"), "Handled test values")
.default(() => "Default handler")
.elseValue("Else handler");
const result = switcher.syncEval("value1"); // Result: 'Handled value1'
const promiseResult = switcher.eval("unknown"); // Result: 'Else handler'
SMMatcher
is a class similar to SMSwitcher
, but designed to evaluate a specific value against multiple conditions more straightforwardly. It offers a direct way to define cases (case
), a default handler (default
), and an alternative value (else
). Unlike Switcher
, Matcher
evaluates the cases at the moment and does not support asynchronous evaluations.
First, import the match
function.
import { match } from "switch-matcher";
const matcher = match<string, string>("value1");
matcher
.case("value1", () => "Handled value1")
.case("value2", "Handled value2")
.case((value) => value.startsWith("test"), "Handled test values")
.default(() => "Default handler")
.else("Else handler");
const result = matcher.value; // Result: 'Handled value1' or 'Else handler' if no matches
If you want to contribute to the project, you can follow these steps:
- Fork the project.
- Create a new branch.
- Make your changes.
- Commit your changes.
- Push your changes to your fork.
- Open a pull request.
And that's it! You can easily contribute to the project and help improve it.
Here we will list the features we plan to add to the library in the future.
This package was developed by LeoLizc. We thank the following people and projects for their contributions:
- leovergaramarq: Brief description of their contribution.
This package is under the MIT license. You can view the license file here.