babel-plugin-pattern-matching
Transform "haskell like" pattern matching.
Syntax analyzing based on bitwise operators like |(OR) and &(AND).
Transforms to javascript function that comes with plugin as a helpers library.
Example
//function declaration //let functionName = pattern-1 | function body for leading pattern // functionName = pattern-2 | function body for leading pattern let factorial = 0 | 1; factorial = n | n * ; //execute; // 6 let fibonacci = 0 | 1; fibonacci = 1 | 1; fibonacci = num | + ; //execute; //89
Available Patterns
Array
//empty arrayx y //array with one or more elementsx y ...ys //array with two or more elements_ y ...ys //array with two or more elements, first one will be skipedall&x y //array with two or more elements, resulting function will receive additional argument 'all' equal to whole arrayx y ...ys x //two arguments as array, where first length >= 2, second >= 1
Object
{} //empty objectx y //object with keys 'x' and 'y'x:n y //object with keys 'x' and 'y', where x will be renamed to nx: m ...rest //object with keys 'x' which is equal object with key 'm', resulting function will receive additional arg. restx: m y: x ...xs //object with keys 'x' and 'y' where y is array that has at least one elementx all&y // two arguments as objects where 1st has x property, second has 'y', 'all' - groupingx: all&y all2&t //nested grouping
Primitives
let pattern = "a" | "result is a"; //for string with 'a' char pattern = 0 | "result is 0"; //for num eq. 0 pattern = true | "result is true"; //for booleans pattern = null | "result is null"; //for null pattern = undefined | "result is undefined"; //for argument that eq. void 0 pattern = NaN | "result is NaN"; //for NaN
Catch All
let pattern = n | "one argument"; pattern = n m | "two arguments"
Transformation
Pattern
let pattern = | "result 0"; pattern = x z | `result `;
Transforms to
let pattern = ;
Pattern
let pattern = n: x | `result `; pattern = n: x all&y ...ys | `result , , , `;
Transforms to
let pattern = ;
Note
The order of patterns is very important
let pattern = x | 'first pattern'; pattern = x y ...ys | 'second pattern'; //first pattern //first pattern
To get correct behavior be careful with ordering!
let pattern = x y ...ys | 'first pattern'; pattern = x | 'second pattern'; //first pattern //second pattern
Install
npm$ npm i --save babel-plugin-pattern-matching yarn$ yarn add babel-plugin-pattern-matching
Usage
Set plugin options using an array of [pluginName, optionsObject]
.
skipLib - won't add the match-helper code to program
enableByComment - will transform patterns just when leading by comment "@match" will be added
//@matchlet pattern = x y ...ys | 'first pattern'; pattern = x | 'second pattern';
Or you can disable transformation in place by comment "@disable-match"
//@disable-matchlet regularOperation = 1 | 0; //1