patrun

Match objects against patterns, most specific first

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 if statements with a table you can add to, list, and inspect.

Take the tutorial Install patrun

patrun 9.0.0 for JavaScript, 0.4.0 for Go · MIT licensed · github.com/rjrodger/patrun

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

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 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.

The documentation #

The documentation is in four parts:

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