-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.mz
524 lines (379 loc) · 10.4 KB
/
README.mz
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# Patroon
Pattern matching in JavaScript without additional syntax.
[![NPM](https://img.shields.io/npm/v/patroon?color=blue&style=flat-square)](https://www.npmjs.com/package/patroon)
[![NPM Downloads](https://img.shields.io/npm/dm/patroon?style=flat-square)](https://www.npmjs.com/package/patroon)
[![100% Code Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square)](#tests)
[![Standard Code Style](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](https://standardjs.com)
[![License](https://img.shields.io/npm/l/patroon?color=brightgreen&style=flat-square)](./LICENSE)
<toc
## Installation
[Patroon][9] is hosted on the NPM repository.
```bash
npm install patroon
```
## Usage
```js node -
const {
// Match Helpers
patroon,
matches,
// Pattern Helpers
every,
some,
multi,
reference,
instanceOf,
_,
// Errors
NoMatchError,
UnevenArgumentCountError,
PatroonError,
} = require('patroon')
```
Let's see what valid and less valid uses of patroon are.
> You can try out patroon over at [RunKit][runkit].
### Primitive
The simplest thing one can do is to match on a [primitive][1].
Numbers:
```js ./tape-test
patroon(
2, 3,
1, 2
)(1)
```
Strings:
```js ./tape-test
patroon(
'a', 'b',
'c', 'd'
)('c')
```
Booleans:
```js ./tape-test
patroon(
true, false,
false, true
)(true)
```
Symbols:
```js ./tape-test
const a = Symbol('a')
const b = Symbol('b')
const c = Symbol('c')
patroon(
a, b,
b, c
)(b)
```
Nil values:
```js ./tape-test
patroon(
null, undefined,
undefined, null,
)(undefined)
```
### Regular Expression
Will check if a Regex matches the passed string using the string's `.test`
method.
```js ./tape-test
patroon(
/^bunion/, 'string starts with bunion',
/^banana/, 'string starts with banana'
)('banana tree')
```
### Placeholder
The `_` is a placeholder/wildcard value that is useful to implement a default case.
```js ./tape-test
patroon(
1, 'value is 1',
'a', 'value is a',
_, 'value is something else'
)(true)
```
We can combine the `_` with other patroon features.
### Object
Patroon can help you match **objects** that follow a certain spec.
```js ./tape-test
patroon(
{b: _}, 'has a "b" property',
{a: _}, 'has an "a" property'
)({b: 2})
```
Next we also match on the key's value.
```js ./tape-test
patroon(
{a: 1}, 'a is 1',
{a: 2}, 'a is 2',
{a: 3}, 'a is 3'
)({a: 2})
```
What about nested objects?
```js ./tape-test
patroon(
{a: {a: 1}}, 'a.a is 1',
{a: {a: 2}}, 'a.a is 2',
{a: {a: 3}}, 'a.a is 3'
)({a: {a: 2}})
```
### Instance
Sometimes it's nice to know if the value is of a certain type. We'll use the
builtin node error constructors in this example.
```js ./tape-test
patroon(
instanceOf(TypeError), 'is a type error',
instanceOf(Error), 'is an error'
)(new Error())
```
Patroon uses `instanceof` to match on types.
```js ./tape-test
new TypeError() instanceof Error
```
Because of this you can match a TypeError with an Error.
```js ./tape-test
patroon(
instanceOf(Error), 'matches on error',
instanceOf(TypeError), 'matches on type error'
)(new TypeError())
```
An object of a certain type might also have values we would want to match on.
Here you should use the every helper.
```js ./tape-test
patroon(
every(instanceOf(TypeError), { value: 20 }), 'type error where value is 20',
every(instanceOf(Error), { value: 30 }), 'error where value is 30',
every(instanceOf(Error), { value: 20 }), 'error where value is 20'
)(Object.assign(new TypeError(), { value: 20 }))
```
Matching on an object type can be written in several ways.
```js ./tape-test > /dev/null
patroon({}, 'is object')({})
patroon(Object, 'is object')({})
```
These are all equivalent.
Arrays can also be matched in a similar way.
```js ./tape-test > /dev/null
patroon([], 'is array')([])
patroon(Array, 'is array')([])
```
A less intuitive case:
```js ./tape-test > /dev/null
patroon({}, 'is object')([])
patroon([], 'is array')({})
```
Patroon allows this because Arrays can have properties defined.
```js ./tape-test > /dev/null
const array = []
array.prop = 42
patroon({prop: _}, 'has prop')(array)
```
The other way around is also allowed even if it seems weird.
```js ./tape-test > /dev/null
const object = {0: 42}
patroon([42], 'has 0th')(object)
```
If you do not desire this loose behavior you can use a predicate to make sure
something is an array or object.
```js ./tape-test > /dev/null
patroon(Array.isArray, 'is array')([])
```
### Reference
If you wish to match on the reference of a constructor you can use the `ref`
helper.
```js ./tape-test
patroon(
instanceOf(Error), 'is an instance of Error',
reference(Error), 'is the Error constructor'
)(Error)
```
### Array
```js ./tape-test
patroon(
[], 'is an array',
)([1, 2, 3])
```
```js ./tape-test
patroon(
[1], 'is an array that starts with 1',
[1,2], 'is an array that starts with 1 and 2',
[], 'is an array',
)([1, 2])
```
> Think of patterns as a subset of the value you are trying to match. In the
> case of arrays. `[1,2]` is a subset of `[1,2,3]`. `[2,3]` is not a subset of
> `[1,2,3]` because arrays also care about the order of elements.
We can also use an object pattern to match certain indexes. The same can be
written using an array pattern and the `_`. The array pattern can become a bit
verbose when wanting to match on a bigger index.
These two patterns are equivalent:
```js ./tape-test
patroon(
{6: 7}, 'Index 6 has value 7',
[_, _, _, _, _, _, 7], 'Index 6 has value 7'
)([1, 2, 3, 4, 5, 6, 7])
```
A function that returns the lenght of an array:
```js ./tape-test
const count = patroon(
[_], ([, ...xs]) => 1 + count(xs),
[], 0
)
count([0,1,2,3])
```
A function that looks for a certain pattern in an array:
```js ./tape-test
const containsPattern = patroon(
[0, 0], true,
[_, _], ([, ...rest]) => containsPattern(rest),
[], false
)
containsPattern([1,0,1,0,0])
```
A toPairs function:
```js ./tape-test
const toPairs = patroon(
[_, _], ([a, b, ...c], p = []) => toPairs(c, [...p, [a, b]]),
_, (_, p = []) => p
)
toPairs([1, 2, 3, 4])
```
> An exercise would be to change toPairs to throw when an uneven length array
> is passed. Multiple answers are possible and some are more optimized than
> others.
### Every
A helper that makes it easy to check if a value passes all patterns.
```js ./tape-test
const gte200 = x => x >= 200
const lt300 = x => x \< 300
patroon(
every(gte200, lt300), 'Is a 200 status code'
)(200)
```
### Some
A helper to check if any of the pattern matches value.
```js ./tape-test
const isMovedResponse = patroon(
{statusCode: some(301, 302, 307, 308)}, true,
_, false
)
isMovedResponse({statusCode: 301})
```
### Multi
Patroon offers the `multi` function in order to match on the value of another
argument than the first one. This is named [multiple dispatch][2].
```js ./tape-test
patroon(
multi(1, 2, 3), 'arguments are 1, 2 and 3'
)(1, 2, 3)
```
### Predicate
By default a function is assumed to be a predicate.
See the [references](#references) section if you wish to match on the reference
of the function.
```js ./tape-test
const isTrue = v => v === true
patroon(
isTrue, 'is true'
)(true)
```
Could one combine predicates with arrays and objects? Sure one can!
```js ./tape-test
const gt20 = v => v > 20
patroon(
[[gt20]], 'is greater than 20'
)([[21]])
```
```js ./tape-test
const gt42 = v => v > 42
patroon(
[{a: gt42}], 'is greater than 42'
)([{a: 43}])
```
### Matches
A pattern matching helper that can help with using patroon patterns in if
statements and such.
```js ./tape-test
const isUser = matches({user: _})
const isAdmin = matches({user: {admin: true}})
const user = {
user: {
id: 2
}
}
const admin = {
user: {
id: 1,
admin: true
}
}
JSON.stringify([isUser(admin), isUser(user), isAdmin(admin), isAdmin(user)])
```
### Custom Helper
It is very easy to write your own helpers. All the builtin helpers are really
just predicates. Let's look at the source of one of these helpers, the simplest
one being the `_` helper.
```js ./tape-test
_.toString()
```
Other more complex helpers like the `every` or `some` helper are also
predicates.
```js ./tape-test
every.toString()
```
See the [./src/index.js][3] if you are interested in the implementation.
### Errors
Patroon has errors that occur during runtime and when a patroon function is
created. It's important to know when they occur.
#### NoMatchError
The no match error occurs when none of the patterns match the value.
```js { ./tape-test 2>&1 || true; } | head -n 6
const oneIsTwo = patroon(1, 2)
oneIsTwo(3)
```
#### UnevenArgumentCountError
Another error that occurs is when the patroon function is not used correctly.
```js { ./tape-test 2>&1 || true; } | head -n 6
patroon(1)
```
#### PatroonError
All errors patroon produces can be matched against the PatroonError using `instanceof`.
```js ./tape-test
const isPatroonError = patroon(instanceOf(PatroonError), 'patroon is causing an error')
isPatroonError(new NoMatchError())
isPatroonError(new UnevenArgumentCountError())
```
## Examples
Patroon can be used in any context that can benefit from pattern matching.
- The following tests show how patroon can help you test your JSON API by
pattern matching on status codes and the body:
https://github.com/bas080/didomi/blob/master/index.test.js.
## Tests
[./src/index.test.js][5] - Contains some tests for edge cases and it defines
some property based tests.
We also care about code coverage so we'll use [nyc][8] to generate a coverage
report.
```bash bash -eo pipefail
# Clean install dependencies.
npm ci &> /dev/null
# Run tests and generate a coverage report
npx nyc npm t | npx tap-nyc
# Test if the coverage is 100%
npx nyc check-coverage
```
## Changelog
See the [CHANGELOG.md][changelog] to know what changes are introduced for each
version release.
## Contribute
You may contribute in whatever manner you see fit. Do try to be helpful and
polite and read the [CONTRIBUTING.md][10].
### Contributors
<contributors
[1]:https://developer.mozilla.org/en-US/docs/Glossary/Primitive
[2]:https://en.wikipedia.org/wiki/Multiple_dispatch
[3]:https://github.com/bas080/patroon/blob/master/src/index.js
[5]:./src/index.test.js
[7]:https://stackoverflow.com/questions/50452844/functional-programming-style-pattern-matching-in-javascript/67376827#67376827
[8]:https://github.com/istanbuljs/nyc
[9]:https://www.npmjs.com/package/patroon
[10]:./CONTRIBUTING.md
[changelog]:./CHANGELOG.md
[runkit]:https://npm.runkit.com/patroon