Overview
x-match-expression is a javascript pattern matching library developed in typescript that can be used standalone in the browser, in node or as ES module.
Installation
- Install it with
npm install --save x-match-expression
or reference it from CDN in the browser
Usage
In the browser (with a script tag)
- Add a script tag
<script src="https://unpkg.com/x-match-expression/dist/browser/index.js" type="application/javascript"></script>
- And later on, use the global
match
function
const financialStatus = ; console; // outputs I keep trying
In Node
const match = ; const isEven = ; console; // outputs true
as ES Module
; const areWeInTheFuture = ; console; // outputs false
API
If you are using typescript or an IDE with autocompletion, just write match. and explore all the options available. Basically you have cases for every javascript primitive type + instance checks. Almost every case method has a companion method ended in "If"; This allows to put an extra predicate if the case is not enough. To end the match expression use default method.
Advanced Usage
Instance check example
; ; ; // returns type Whatever .caseInstanceIfFatalError, _.id === 404 `No content found at ` .caseInstanceFatalError, `Error # received` .caseInstanceWarning, `Warning : ` .caseInstanceMailMessage, `You received a message from ` .default"Unknown information received";
Float comparison
; ;;; .caseEqualc, "This number is 0.6" .caseAlmostEqualc, "The number is not exactly 0.6, but it is very close" // <-- this will match .default"This number is not 0.6 at all";
Custom test that fails
; { throw "Error!"; // <-- look at this} const value = // <-- custom tests doesn't raise exceptions, they simple return false ;
With union type as return
; .caseString`` .caseNumbern*2 .default0;