egna
Pattern matching in JS
;
Example
; let car = async make: 'Toyota' year: 1968 ; ; // prints "Toyota from 1968"
Match anything
;
Scenarios
Filter/map/reduce/etc
; let cars = emissions: 2500 emissions: 60000 ; let greenCars = cars; // greenCars = [{ emissions: 2500 }]
Promises
The egna
module adds a match function to Promise.prototype.match
.
Meaning you can call match on any Promise generated from the global Promise
prototype.
; // only have to import once anywhere in the project let promise = async "hello"; ;// return value of the matched handler is passed along the promise chain
Pattern reuse
A call to match returns function loaded with the patterns and handlers. This function can be stored and used whenever.
; let httpPattern = ; // Use it multiple timesconst msg = ;const msg2 = ;
Matchlet functions
A function anywhere in a pattern will be evaluated in place of the usual comparison, returning true/false.
Matchlet-generators included in egna:
Name | Matches |
---|---|
gt |
Greater than arg |
lt |
Less than arg |
op |
Optional, value exists in the argument array. |
Use egna's matchlets
;
or make your own
const even = n % 2 == 0; 34 // returns 'even number'
More examples
tc39 proposal example: