JSPM

  • Created
  • Published
  • Downloads 77
  • Score
    100M100P100Q73615F
  • License GPL-3.0

Pattern matching library

Package Exports

  • patroon

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (patroon) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Patroon

NPM NPM Downloads 100% Code Coverage Dependency Status Standard Code Style

Pattern matching in JavaScript without additional syntax.

Installation

Patroon is hosted on the NPM repository.

npm install patroon

Usage

Let's see what valid and less valid uses of patroon are.

Primitives

The simplest thing one can do is to match on a primitive.

Numbers:

patroon(
  2, 3,
  1, 2
)(1)
2

Strings:

patroon(
  'a', 'b',
  'c', 'd'
)('c')
d

Booleans:

patroon(
  true, false,
  false, true
)(true)
false

Symbols:

const a = Symbol('a')
const b = Symbol('b')
const c = Symbol('c')

patroon(
  a, b,
  b, c
)(b)
Symbol(c)

Nil values:

patroon(
  null, undefined,
  undefined, null,
)(undefined)
null

Regular Expressions

Will check if a Regex matches the passed string using the string's .test method.

patroon(
  /^bunion/, 'string starts with bunion',
  /^banana/, 'string starts with banana'
)('banana tree')
string starts with banana

Placeholders

The _ is a placeholder/wildcard value that is useful to implement a default case.

patroon(
  1, 'value is 1',
  'a', 'value is a',
  _, 'value is something else'
)(true)
value is something else

We can combine the _ with other patroon features.

Objects

Patroon can help you match objects that follow a certain spec.

patroon(
  {b: _}, 'has an "a" property',
  {a: _}, 'has a "b" property'
)({b: 2})
has an "a" property

Next we also match on the key's value.

patroon(
  {a: 1}, 'a is 1',
  {a: 2}, 'a is 2',
  {a: 3}, 'a is 3'
)({a: 2})
a is 2

What about nested objects?

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}})
a.a is 2

Types

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.

patroon(
  TypeError, 'is a type error',
  Error, 'is an error'
)(new Error())
is an error

Patroon uses instanceof to match on types.

new TypeError() instanceof Error
true

Because of this you can match a TypeError with an Error.

patroon(
  Error, 'matches on error',
  TypeError, 'matches on type error'
)(new TypeError())
matches on error

An object of a certain type might also have values we would want to match on. Here you should use the typed helper.

Simply pass a pattern as the second argument of typed.

patroon(
  typed(TypeError, { value: 20 }), 'type error where value is 20',
  typed(Error, { value: 30 }), 'error where value is 30',
  typed(Error, { value: 20 }), 'error where value is 20'
)(Object.assign(new TypeError(), { value: 20 }))
type error where value is 20

Matching on an object type can be written in several ways.

patroon({}, 'is object')({})
patroon(Object, 'is object')({})
patroon(typed(Object), 'is object')({})

These are all equivalent.

Arrays can also be matched in a similar way.

patroon([], 'is array')([]),
patroon(Array, 'is array')([]),
patroon(typed(Array), 'is array')([])
is array

Reference

If you wish to match on the reference of a constructor you can use the ref helper.

patroon(
  1, 'is 1',
  Number, 'is a number',
  ref(Number), 'is the Number constructor',
)(Number)
is the Number constructor

Arrays

patroon(
  [], 'is an array',
)([1, 2, 3])
is an array
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])
is an array that starts with 1

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.

A function that looks for a certain pattern in an array:

const containsPattern = patroon(
  [0, 0], true,
  [_, _], ([, ...rest]) => containsPattern(rest),
  [], false
)

containsPattern([1,0,1,0,0])
true

A toPairs function:

const toPairs = patroon(
  [_, _], ([a, b, ...c], p = []) => toPairs(c, [...p, [a, b]]),
  _, (_, p = []) => p
)

toPairs([1, 2, 3, 4])
toPairs([1, 2, 3, 4])
[ [ 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.

Predicates

By default a function is assumed to be a predicate.

See the [reference][#reference] section if you wish to match on the reference of the function.

const isTrue = v => v === true

patroon(
  isTrue, 'is true'
)(true)
is true

Could one combine predicates with arrays and objects? Sure one can!

const gt20 = v => v > 20

patroon(
  [[gt20]], 'is greater than 20'
)([[21]])
is greater than 20
const gt42 = v => v > 42

patroon(
  [{a: gt42}], 'is greater than 42'
)([{a: 43}])
is greater than 42

Custom Helpers

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.

const _ = () => true

Other more complex helpers like the typed helper are also predicates. See the [./src/index.js][3] if you are interested in their implementation.

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 to generate a coverage report.

Coverage

set -eo pipefail

# Install and prune dependencies
{
  npm i
  npm prune
} &> /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
    > patroon@0.1.4 test
    > tape ./src/index.test.js
    -------------|---------|----------|---------|---------|-------------------
    File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -------------|---------|----------|---------|---------|-------------------
    All files    |     100 |      100 |     100 |     100 |                   
     helpers.js  |     100 |      100 |     100 |     100 |                   
     index.js    |     100 |      100 |     100 |     100 |                   
     walkable.js |     100 |      100 |     100 |     100 |                   
    -------------|---------|----------|---------|---------|-------------------

  total:     5
  passing:   5

  duration:  1s

StackOverflow

This project is mentioned in the following StackOverflow question.

Contribute

You may contribute in whatever manner you see fit. Do try to be helpful and polite and read the CONTRIBUTING.md.