Pampy.js: Pattern Matching for JavaScript
Pampy.js is pretty small (250 lines), reasonably fast, and often makes your code more readable, and easier to reason about. There is also a Python version of Pampy.
You can write many patterns
Patterns are evaluated in the order they appear.
You can write Fibonacci
The operator _ means "any other case I didn't think of". If you already use _
, you can require ANY
, which is exactly the same.
let match _ = ; { return ;}
You can write a Lisp calculator in 5 lines
let match REST _ = ; { return ;}let a + b;let a - b;let l; ; // => 3; // => 3; // => 6
You can match so many things!
let match _ = ;
You can match TAIL
let match _ TAIL = ; x = 1 2 3; ; // => [2, 3] ; // => [1, [2, 3])
You can nest lists and tuples
let match _ TAIL = ; x = 1 2 3 4; ; // => [1, [2, 3], 4]
You can nest dicts. And you can use _ as key!
pet = type: 'dog' details: age: 3 ; ; // => 3 ; // => ['details', 3]
Admittedly using _
as key is a bit of a trick, but it works for most situations.
You can use functions as patterns
You can pass [pattern, action] array pairs to matchPairs for better Prettier formatting.
{ return }
All the things you can match
Pattern Example | What it means | Matched Example | Arguments Passed to function | NOT Matched Example |
---|---|---|---|---|
"hello" |
only the string "hello" matches |
"hello" |
nothing | any other value |
Number |
Any javascript number | 2.35 |
2.35 |
any other value |
String |
Any javascript string | "hello" |
"hello" |
any other value |
Array |
Any array object | [1, 2] |
[1, 2] |
any other value |
_ |
Any object | that value | ||
ANY |
The same as _ |
that value | ||
[1, 2, _] |
A list that starts with 1, 2 and ends with any value | [1, 2, 3] |
3 |
[1, 2, 3, 4] |
[1, 2, TAIL] |
A list that start with 1, 2 and ends with any sequence | [1, 2, 3, 4] |
[3, 4] |
[1, 7, 7, 7] |
{type:'dog', age: _ } |
Any dict with type: "dog" and with an age |
{type:"dog", age: 3} |
3 |
{type:"cat", age:2} |
{type:'dog', age: Number } |
Any dict with type: "dog" and with an numeric age |
{type:"dog", age: 3} |
3 |
{type:"dog", age:2.3} |
x => x > 3 |
Anything greather than 3 | 5 |
3 |
2 |
null |
only null |
null |
nothing | any other value |
undefined |
only undefined |
undefined |
nothing | any other value |
How to install
npm install pampy