pattern-match-es
Rust inspired pattern matching for JavaScript.
More info on the ECMAScript Pattern Matching proposal.
Usage
Install:
npm i pattern-match-es --save
And then use like so:
;
Or use via a CDN like unpkg:
;
There is also a lite
version available, that doesn't support matching objects and arrays, but is a hell of a lot smaller.
;
Examples
Basic example
const boolean = false;const binary = false 0 true 1; binary; // 0
Multiple values
const num = 1; 1 2 3 4 5 { console } 6 { console }; // "lower than 5"
Default case
const num = 5; 1 { console } 2 { console } { console }; // "neither"
Predicates
const num = 9; 1 2 3 4 5 { console } num > 6 { console }; // "higher than 6"
Objects
const user = name: 'Steve' ; name: 'Steve' { console } name: 'John' { console }; // "Steve"
Arrays
const array = 1 2 3; 1 2 { console } 1 2 3 { console }; // "three items"
Handling responses
const res = await ; 200 console 404 console status > status >= 400 console
With Preact
; { const count setCount = ; return html` - + `;} ;
With LitElement
;; const loadingTemplate = html`Loading...`; static { return state: type: String ; } async { super; thisstate = 'loading'; try await ; thisstate = 'success'; catch thisstate = 'error'; } { return 'loading' loadingTemplate 'error' html`☹️ Error!` 'success' html`🎉 Success!` }
Redux reducers
const initialState = filter: 'all' todos: text: 'Finish demos' done: false const options = type: undefined filter: undefined index: undefined text: undefined ; { return ...options type: 'set-visibility-filter' filter ...state filter ...options type: 'add-todo' text ...state todos: ...statetodos text done: false ...options type: 'toggle-todo' index ...state todos: statetodos state }