# match objects against patterns, most specific first

patrun finds the pattern that best matches an object's properties, from a set of patterns, without a chain of if statements. It ships for JavaScript and TypeScript on npm, and for Go.

<section class="intro">
<span class="word">patrun</span>
<h1>Match objects against patterns, most specific first</h1>
<p class="lede">patrun holds a set of patterns, each with its data, and answers a query with the data of the pattern that matches it best. A pattern with more matching properties beats one with fewer, so the special cases sit beside the general ones and win where they apply. It replaces a chain of <code>if</code> statements with a table you can add to, list, and inspect.</p>
<p class="actions"><a class="button primary" href="/tutorials/first-router.html">Take the tutorial</a> <a class="button" href="/how-to/install.html">Install patrun</a></p>
<p class="meta">patrun 9.0.0 for JavaScript, 0.4.0 for Go · MIT licensed · <a href="https://github.com/rjrodger/patrun">github.com/rjrodger/patrun</a></p>
</section>

Here a router holds three patterns, and each query gets the data of the most specific one it matches:

```js
const patrun = require('patrun')

const pm = patrun()
  .add({ a: 1 }, 'A')
  .add({ a: 1, b: 1 }, 'B')
  .add({ a: 1, b: 2 }, 'C')

pm.find({ a: 1 }) // → 'A'
pm.find({ a: 1, b: 1 }) // → 'B'  more specific wins
pm.find({ a: 1, z: 9 }) // → 'A'  z is in no pattern, so it is ignored
pm.find({ a: 2 }) // → null
```

The order in which the patterns were added makes no difference. The [Seneca](https://senecajs.org) framework uses patrun to choose the action that handles each message.

## Install

| Language | Command |
|---|---|
| JavaScript or TypeScript, Node.js 24 or later | `npm install patrun` |
| Go 1.24 or later | `go get github.com/rjrodger/patrun/go` |

For more information, see [Install patrun](https://rjrodger.github.io/patrun/how-to/install.html).

## The documentation

The documentation is in four parts:

- [Tutorials](https://rjrodger.github.io/patrun/tutorials/). Lessons that take you from an empty file to a working router, in JavaScript or in Go.
- [How-to guides](https://rjrodger.github.io/patrun/how-to/). Recipes for one task each, such as matching a range of numbers or listing what a router holds.
- [Reference](https://rjrodger.github.io/patrun/reference/). Every function and type of both ports, and the rules that order the matches, stated in full.
- [Explanation](https://rjrodger.github.io/patrun/explanation/). Why patrun picks the match it does, and how its tree finds it.
