npm.io
8.0.0 • Published 8h ago

patrun

Licence
MIT
Version
8.0.0
Deps
1
Size
228 kB
Vulns
0
Weekly
0
Stars
143

patrun

npm version Build Status Coverage Status Dependency Status DeepScan grade Maintainability

A fast pattern matcher on JavaScript object properties. Builds a decision tree so you can pick out the most-specific match for a given subject without writing chains of if statements. Used by the Seneca framework to dispatch actions.

A Go port is also available — see go/README.md.

From the Irish patrún: pattern. Pronounced pah-troon.


Tutorial: your first patrun

Install:

npm install patrun

Register a few patterns, then look one up:

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: 2 })           // → null  (no match)
pm.find({ a: 1, b: 1 })     // → 'B'   (more specific wins)
pm.find({ a: 1, b: 2 })     // → 'C'
pm.find({ a: 1, z: 9 })     // → 'A'   (unknown keys ignored)

The matcher stores patterns in a trie keyed by sorted property names, so find makes the minimum number of comparisons needed to pick out the most specific match. It's query-by-example for property sets.

You're matching a subset, so your input can contain any number of extra properties — they're ignored.


How-to guides

Pick the most specific match (the default)

The two rules that govern every match:

  1. More specific matches beat less specific ones — more matched key/value pairs always win.
  2. Between matches with the same number of pairs, property names are checked in alphabetical order, so insertion order doesn't matter.
const pm = patrun()
  .add({ a: 0 },          'A')
  .add({ b: 1 },          'B')
  .add({ c: 2 },          'C')
  .add({ a: 0, b: 1 },    'AB')

pm.find({ a: 0 })            // → 'A'
pm.find({ a: 0, b: 1 })      // → 'AB'  (more specific than {a:0})
pm.find({ a: 0, c: 2 })      // → 'A'   (a comes before c)
pm.find({ b: 1, c: 2 })      // → 'B'   (b comes before c)

Rule 1 comes first. A pattern with more pairs wins even when its keys come later in the alphabet:

const pm = patrun()
  .add({ a: 1 },          'A')
  .add({ b: 2, c: 3 },    'BC')

pm.find({ a: 1, b: 2, c: 3 })  // → 'BC'  (two pairs beat one)
pm.find({ a: 1, b: 2 })        // → 'A'   (only {a:1} matches)
Know which pattern wins when several match

For any subject, the patterns that match it come in one order, and find gives the first. The order does not depend on the order in which the patterns were added. It is decided by these three tests, in turn:

  1. The pattern with more pairs comes first.
  2. Of patterns with as many pairs, the one whose keys come first: the keys of each, in alphabetical order, are compared one by one.
  3. Of patterns with the same keys, the one with an exact value at the first key where the other has a '*'.

Two different patterns that match the same subject always differ in one of the three, so there is never a tie.

With gex or interval on, test 3 has more steps. At the first key where two patterns differ, an exact value comes first, then a glob, then an interval, then '*', and of two globs or two intervals the narrower. See Match values with glob expressions and Match numbers by interval.

The order of keys is alphabetical unless you say which keys come first: see Choose which keys come first.

The order always puts the narrower pattern first. One pattern is narrower than another when it has every pair of the other, or, where the other has a '*', the key: every subject that matches it then matches the other too. So { a: 1, b: 2 } comes before { a: 1 }, and { a: 1, b: 2 } before { a: 1, b: '*' }. The tests only ever choose between patterns of which neither is the narrower, and that holds for patterns that have no key in common too. Test 2 decides between them:

const pm = patrun()
  .add({ b: 2 },          'B')
  .add({ a: 1 },          'A')
  .add({ b: 2, c: 3 },    'BC')
  .add({ a: 1, d: 4 },    'AD')

pm.find({ a: 1, b: 2 })              // → 'A'   a comes before b
pm.find({ a: 1, b: 2, c: 3, d: 4 })  // → 'AD'  a, d comes before b, c

The order between two unrelated patterns is fixed, but it is only alphabetical. If a subject that matches both should get something else, say so with a pattern for the two together. It has more pairs, so it wins:

pm.add({ a: 1, b: 2 }, 'A-AND-B')
pm.find({ a: 1, b: 2 })              // → 'A-AND-B'

Keys are compared by code point, so upper case comes before lower case: Z before a.

Choose which keys come first

Test 2 above compares keys in alphabetical order. If some keys should decide before the others, name them with the order option. They come first, in the order you give, and every other key comes after them, in alphabetical order as before:

const plain = patrun()
  .add({ cmd: 'list' },  'CMD')
  .add({ srv: 'user' },  'SRV')

plain.find({ cmd: 'list', srv: 'user' })  // → 'CMD'  cmd comes before srv

const pm = patrun({ order: ['srv'] })
  .add({ cmd: 'list' },  'CMD')
  .add({ srv: 'user' },  'SRV')

pm.find({ cmd: 'list', srv: 'user' })     // → 'SRV'  srv comes first

With { order: ['srv', 'role'] } the order of keys is srv, then role, then the rest alphabetically. So of two patterns with as many pairs, one that has srv comes before one that lacks it.

The order of keys is all that the option changes. A pattern with more pairs still comes first, whatever its keys, and so does the narrower of two patterns:

pm.add({ cmd: 'list', role: 'admin' }, 'CMD-ROLE')

pm.find({ cmd: 'list', role: 'admin', srv: 'user' })
// → 'CMD-ROLE'  two pairs beat one

Test 3 looks at the keys in the same order. Of two patterns with the same keys, the one with an exact value at the first key in the order comes first:

const stars = patrun({ order: ['srv'] })
  .add({ cmd: 'list', srv: '*' },   'ANY-SRV')
  .add({ cmd: '*', srv: 'user' },   'ANY-CMD')

stars.find({ cmd: 'list', srv: 'user' })  // → 'ANY-CMD'  exact at srv

With no order the first key is cmd, and the answer is 'ANY-SRV'.

A matcher keeps the order it was made with. It is the order in which collect and list give patterns, and the order of the keys that toString prints.

The option is an array that names each key once. A key is a string that is not empty. patrun throws a TypeError for anything else. It may name keys that no pattern has, which changes nothing.

Require all keys to match

Pass true as the second argument to find for exact matching. The pattern must then have every key that the subject has a value for:

const pm = patrun()
  .add({ a: 0 },          'A')
  .add({ a: 0, b: 1 },    'AB')

pm.find({ a: 0, b: 1 }, true)  // → 'AB'
pm.find({ a: 0, b: 9 }, true)  // → null  (b doesn't match)
pm.find({ a: 0, z: 9 }, true)  // → null  (no pattern has both a and z)
pm.find({ a: 0, z: 9 })        // → 'A'   (without it, z is ignored)
Require a key, whatever its value

A pattern value of '*' takes any value. The subject must have a value for the key, and it does not matter what the value is:

const pm = patrun()
  .add({ role: 'math', cmd: 'sum' }, 'SUM')
  .add({ role: 'math', cmd: '*' },   'ANY')

pm.find({ role: 'math', cmd: 'sum' })      // → 'SUM'  an exact value comes first
pm.find({ role: 'math', cmd: 'product' })  // → 'ANY'
pm.find({ role: 'math', cmd: '' })         // → 'ANY'  the empty string is a value
pm.find({ role: 'math' })                  // → null   no cmd, so no match

This needs no option, and means the same when gex is on. A star counts as a matched pair, so the pattern with the most pairs still wins. Between patterns with the same keys, the one with an exact value comes before the one with a star.

Collect every match along the path

Pass true as the third argument to find to get the data of every pattern that matches, a pattern before those that add pairs to it:

const pm = patrun()
  .add({},                 'ROOT')
  .add({ a: 1 },           'A')
  .add({ a: 1, b: 1 },     'AB')
  .add({ a: '*', b: 1 },   'SB')

pm.find({ a: 1, b: 1 }, false, true)
// → ['ROOT', 'A', 'AB', 'SB']

With exact as well, you get only the patterns that have every key of the subject, in the order find would pick them. The first is what findexact returns:

pm.find({ a: 1, b: 1 }, true, true)
// → ['AB', 'SB']
Match values with glob expressions

Enable the gex matcher to use * and ? wildcards within pattern values (powered by gex):

const pm = patrun({ gex: true })
  .add({ a: 10 },             'A')
  .add({ a: '1*' },           'AA')
  .add({ a: '*' },            'AAA')
  .add({ b: 1, c: 'x*y' },    'BC')

pm.find({ a: 10 })            // → 'A'    exact
pm.find({ a: 12 })            // → 'AA'   glob
pm.find({ a: 2 })             // → 'AAA'  star
pm.find({ b: 1, c: 'xhy' })   // → 'BC'   exact + glob

A * on its own is not a glob. It is the star of Require a key, whatever its value, which is the same with or without gex.

The more-specific rule applies as usual: a glob match counts as a matched pair, so the pattern with the most pairs wins. Between patterns with the same number of pairs, an exact value beats a glob, and a glob beats the star.

Of two globs for the same key that both match, the narrower wins, whichever was added first. A glob is narrower than another when it takes only values that the other takes too. The globs of a key come in this order:

  1. The glob with more fixed characters comes first.
  2. Then the one with more ?s.
  3. Then the one with fewer *s.
  4. Then the one whose text comes first.
const pm = patrun({ gex: true })
  .add({ a: 'a*' },   'STARTS-A')
  .add({ a: 'ab*' },  'STARTS-AB')
  .add({ a: 'a?' },   'A-AND-ONE')
  .add({ a: '*a*' },  'HAS-A')

pm.find({ a: 'abc' })  // → 'STARTS-AB'  two fixed characters
pm.find({ a: 'ax' })   // → 'A-AND-ONE'  a? before a*
pm.find({ a: 'axy' })  // → 'STARTS-A'   a* before *a*
pm.find({ a: 'xa' })   // → 'HAS-A'

** is a star itself and *? a question mark itself. They are fixed characters like any other. Where neither of two globs is the narrower, as with 1* and *2, the order is still fixed, by these same tests.

Match numbers by interval

Enable the interval matcher to give a pattern a range of numbers for a value:

const pm = patrun({ interval: true })
  .add({ x: '<10' },     'low')
  .add({ x: '[10,20]' }, 'mid')
  .add({ x: '>20' },     'high')

pm.find({ x: 5 })      // → 'low'
pm.find({ x: 15 })     // → 'mid'
pm.find({ x: '42' })   // → 'high'
pm.find({ x: 'abc' })  // → null

An interval is written with an operator or as a range:

Form Matches
>10, >=10, <10, <=10 numbers on that side of 10
=10 the number 10
[10,20] 10 to 20, both included
(10,20) 10 to 20, both left out
(10,20], [10,20) one end included
10..20 10 to 20, both included
>=10&<20 both tests
<10||>20 either test

A value needs an operator or a range to be an interval. A number on its own, such as 10 or 1.0, is an exact value, and is matched as text: write =10 to match the number.

A subject's value matches an interval when it is a number in it. It is a number only when the whole of it is a decimal number: an optional sign, digits with an optional fraction, and an optional exponent, as in 15, -1.5 or 2e3. A value with spaces, or with anything after the number, is no number, so '15 ' and '15px' match no interval. Neither do Infinity, NaN, hexadecimal such as 0x10, or underscores. The numbers in a pattern are read the same way, and a value with any other, such as >0x10, is an exact value.

An exact value beats an interval, and an interval beats the star. Of two intervals for the same key that both match, the narrower wins, whichever was added first. The intervals of a key come in this order:

  1. An interval with two ends, then one that goes on for ever one way, such as >10, then one with a gap, such as <10||>20.
  2. With two ends, the shorter first, and one number before any. One way for ever, the one that starts further along: >20 before >10. With a gap, the longer gap first.
  3. Then the one with fewer of its ends included: (10,20), then [10,20), then [10,20].
const pm = patrun({ interval: true })
  .add({ x: '>10' },      'OVER-10')
  .add({ x: '[10,20]' },  'TEN-TO-TWENTY')
  .add({ x: '[14,16]' },  'AROUND-15')
  .add({ x: '=15' },      'FIFTEEN')

pm.find({ x: 15 })  // → 'FIFTEEN'
pm.find({ x: 16 })  // → 'AROUND-15'
pm.find({ x: 18 })  // → 'TEN-TO-TWENTY'
pm.find({ x: 30 })  // → 'OVER-10'

Where neither of two intervals is the narrower, the order is still fixed: by these tests, and then by their numbers, the lower first.

An interval can be written in more than one way: [10,20], 10..20 and >=10&<=20 are one pattern. Adding it again, however written, replaces its data, and remove and list find it by any spelling. =1 and [1,1] take the same number with different tests, and are two patterns.

interval can be turned on together with gex. A value can then match a glob and an interval for the same key, as 15 matches 1* and [10,20]. Every glob comes before every interval.

Build a decision tree of business rules

A larger example — sales-tax rules with country, state, city, and type overrides:

function I(val) { const rate = () => val; rate.val = val; return rate }

const salestax = patrun()
  .add({},                                           I(0.0))

  .add({ country: 'IE' },                            I(0.25))
  .add({ country: 'UK' },                            I(0.20))
  .add({ country: 'DE' },                            I(0.19))

  .add({ country: 'IE', type: 'reduced' },           I(0.135))
  .add({ country: 'IE', type: 'food' },              I(0.048))
  .add({ country: 'UK', type: 'food' },              I(0.0))
  .add({ country: 'DE', type: 'reduced' },           I(0.07))

  .add({ country: 'US' },                            I(0.0))
  .add({ country: 'US', state: 'AL' },               I(0.04))
  .add({ country: 'US', state: 'AL', city: 'Montgomery' }, I(0.10))
  .add({ country: 'US', state: 'NY' },               I(0.07))
  .add({ country: 'US', state: 'NY', type: 'reduced' }, function under110(net) {
    return net < 110 ? 0.0 : salestax.find({ country: 'US', state: 'NY' })
  })

salestax.find({ country: 'IE', type: 'food' })(99)            // 0.048
salestax.find({ country: 'US', state: 'AL', city: 'Montgomery' })(99) // 0.1
List every registered pattern

Pass no argument (or an empty object) to list to dump everything:

pm.list()

Pass a partial pattern to filter:

const pm = patrun()
  .add({ a: 1, b: 1 }, 'B1')
  .add({ a: 1, b: 2 }, 'B2')

pm.list({ a: 1 })
// [ { match: { a: '1', b: '1' }, data: 'B1' },
//   { match: { a: '1', b: '2' }, data: 'B2' } ]

pm.list({ a: 1, b: '*' })   // the patterns with a:1 that have a b
pm.list({ a: 1, c: 1 })     // []  (no matches)

A value of the partial pattern is had exactly, or is '*', which asks only that a pattern has the key. It is never a test of other values: with gex on, { a: 'x*' } lists the patterns that have the glob x* itself, and not those with values that x* would take. An interval is asked for by any of its spellings. Omitted keys are not equivalent to '*' — you must specify each key you want to filter on. The empty pattern {} has no pairs, so it is listed only when the partial pattern has none.

Patterns are listed key by key, in the matcher's order of keys, and the values of a key in ranking order: the exact values, whole numbers first, in numeric order, and then the others as text; then the globs; then the intervals; then '*'. A pattern comes before those that add pairs to it. The order never depends on the order of adding:

const pm = patrun()
  .add({ a: 'x' }, 'X').add({ a: 10 }, 'TEN')
  .add({ a: '*' }, 'ANY').add({ a: 9 }, 'NINE')

pm.list().map((entry) => entry.data)
// [ 'NINE', 'TEN', 'X', 'ANY' ]

Pass true as the second argument to list only the patterns that have no other keys than the partial pattern's.

Remove a pattern
pm.remove({ a: 1, b: 1 })

remove clears the data of exactly the pattern it is given. A pattern that was never added changes nothing. Adding a pattern with no data does the same:

pm.add({ a: 1, b: 1 }, null)   // as pm.remove({ a: 1, b: 1 })
Customise stored data

Pass a function as the constructor argument to wrap stored data. It runs at add time and may return a transform applied at find time (plus an optional remove handler).

Add a constant property to every stored pattern:

const alwaysAddFoo = patrun(function (pat) {
  pat.foo = true
})

alwaysAddFoo.add({ a: 1 }, 'bar')
alwaysAddFoo.find({ a: 1 })             // null
alwaysAddFoo.find({ a: 1, foo: true })  // 'bar'

Transform found data:

const upperify = patrun(function (pat) {
  return function (args, data) {
    return ('' + data).toUpperCase()
  }
})

upperify.add({ a: 1 }, 'bar')
upperify.find({ a: 1 })  // 'BAR'

Allow multiple matches per pattern:

const many = patrun(function (pat, data) {
  const items = this.find(pat, true) || []
  items.push(data)

  return {
    find:   (args, data) => items.length ? items : null,
    remove: (args, data) => { items.pop(); return items.length === 0 }
  }
})

many.add({ a: 1 }, 'A')
many.add({ a: 1 }, 'B')
many.find({ a: 1 })   // ['A', 'B']
many.remove({ a: 1 })
many.find({ a: 1 })   // ['A']

The patterns alone decide which pattern matches. find picks the most specific pattern as always, and only then calls that pattern's function on its data. Whatever the function returns is the answer, null included: find does not go on to another pattern. collect and list give the data as it was stored, and each entry of list has the pattern's function as find.

Inspect the decision tree

toString renders the tree as a flat list of patterns and their data, optionally with a custom formatter:

console.log(salestax.toString(f => f.name + ':' + f.val))
//  -> :0
// city=Montgomery, country=US, state=AL -> :0.1
// country=IE -> :0.25
// country=IE, type=food -> :0.048
// ...

toJSON(indent) returns the raw internal trie as JSON, useful for debugging. The text is the same for the same patterns and data, in whatever order they were added, so two matchers can be compared by it.

Use it from TypeScript

The package has its own types. A matcher can be told what its patterns hold, and find then answers that, or null:

import patrun from 'patrun'
import type { PatrunRouter } from 'patrun'

const tax: PatrunRouter<number> = patrun<number>({ order: ['country'] })

tax.add({ country: 'IE' }, 0.25).add({ country: 'IE', type: 'food' }, 0.048)

const rate: number | null = tax.find({ country: 'IE', type: 'food' })
const rates: number[] = tax.find({ country: 'IE' }, false, true)

tax.add({ country: 'IE' }, 'high')    // does not compile: the data is a number
tax.add({ country: ['IE'] }, 0.25)    // does not compile: a value is not an array

A pattern may be an object of any type whose members are all strings, numbers or booleans, so one typed by an interface will do as well as a literal. With no type given, a matcher holds anything, as before.

A customizer whose function changes what find answers gives that as a second type: patrun<string, string[]>(...) holds strings and finds lists of them. See Types.


Reference

patrun(custom?)

Create a new pattern matcher. The module is this function: require('patrun'), or import patrun from 'patrun'. It is also exported by name as Patrun, and both can be called with new. Gex is the glob library that the gex option uses. custom may be:

  • omitted — plain matcher. A pattern value of '*' takes any value, here and with every option.
  • { gex: true } — enable glob matching on values that have a * or a ? in them. A * on its own is not a glob.
  • { interval: true } — enable matching of numbers by interval, on values such as >10 or [10,20]. See Match numbers by interval. Both options can be on at once.
  • { order: ['srv', 'role'] } — the keys that come first in the matcher's order of keys, in the order given. Every other key comes after them, in alphabetical order. The option is an array of strings, none empty and none twice, or patrun throws a TypeError. It goes with the other options. See Choose which keys come first.
  • a function — runs at every add to rewrite the pattern and optionally return a find transform / remove handler. See Customise stored data. Set an option on the function itself to have both: custom.order = ['srv'].
.add(pattern, data)

Register pattern and its associated data. Returns the matcher for chaining. A value of '*' takes any value: see Require a key, whatever its value.

pattern must be a map, and none of its keys may be the empty string. Each of its values must be a string, a number or a boolean. A key whose value is null or undefined is left out. Otherwise add throws a TypeError and changes nothing: see Maps only and Strings everywhere.

data may be anything but null and undefined, which are no data: with either, add leaves the pattern holding nothing, as remove does.

.find(subject, exact?, collect?)

Look up the most-specific match for subject. Unknown keys in subject are ignored. Only string, number and boolean values in subject can match: see Strings everywhere. Nothing matches a subject that is not a map: see Maps only.

  • exact (boolean, default false) — require the pattern to have every key that subject has a value for.
  • collect (boolean, default false) — return an array with the data of every pattern that matches, instead of the data of the most specific one. With exact as well, of every pattern that matches and has every key that subject has a value for.

Returns the data, or null if no pattern matched. With collect, returns an array, which is empty if no pattern matched.

.findexact(subject)

Shorthand for .find(subject, true).

.list(partial?, exact?)

Return the registered patterns that have every pair of partial, a partial pattern. A value of it is had exactly, or is '*' for any value. Omitted keys are not wildcards. With no argument, or null, lists every registered pattern. Returns an array of { match, data, find }, in the order given under List every registered pattern.

  • exact (boolean, default false) — list only the patterns that have no other keys than those of partial.

A partial that is not a map, or that has a pair no pattern can have, with the empty string as its key or a value that is not a string, a number or a boolean, lists nothing.

.remove(pattern)

Clear the data stored at exactly pattern. A pattern that was never added changes nothing. Like add, it throws a TypeError for a pattern that add would refuse.

.toString(formatter?, tree?)

Render the decision tree.

  • formatter(data) — optional custom formatter for stored values.
  • tree (boolean, default false) — if true, print as an indented tree instead of a flat list.

patrun.inspect is an alias for toString.

.toJSON(indent?)

Return the internal trie as JSON text, indented as JSON.stringify would with indent: a number of spaces, or a string of spaces and tabs. A node has, in this order, k, its key; v, the node of each exact value of the key and of the *; g, the matchers' values for the key, each with its own node as keymap; s, the skip path, to the patterns that do not have the key; and d, the data. A member that a node does not have is left out.

The values of a key are written in the order that list gives them, and the matchers' values in ranking order. So the text depends only on the patterns and their data, and not on the order of adding. An interval that was written in more than one way shows as it was last written. A function is written as "[Function]".

JSON.stringify calls toJSON itself for a matcher that it comes to, with the key that the matcher is the value of. A key is not an indent, so a string that is not blank is not taken for one. The matcher is then written as its text with no indent, as a string: JSON.stringify({ r: matcher }) gives {"r":"{\"k\": ... }"}.

Types

For TypeScript. Each is exported by name: import type { PatrunRouter } from 'patrun'.

Type What it is
PatrunRouter<Data, Found> A matcher. Data is what a pattern holds, and Found what find answers, which is Data unless a customizer's function answers otherwise. Both are any if not given.
PatrunOptions The options: gex, interval and order.
PatrunPattern A pattern: a map of keys to values.
PatrunValue A value of a pattern: a string, a number or a boolean. null and undefined are in the type too, as a key with either is left out.
PatrunPatternOf<P> What an object of type P must be for add, remove and list to take it: each of its members a PatrunValue.
PatrunSubject What find is asked about: any map.
PatrunEntry<Data, Found> One of the patterns that list gives: match, the pattern with its values as strings, data, and find, the customizer's function if there is one.
PatrunCustomizer<Data, Found> A customizer: the function that add calls with each pattern and its data. The data is null or undefined when add is given none.
PatrunFind<Data, Found>, PatrunRemove<Data> The two functions that a customizer may give for a pattern.
PatrunMaker The type of patrun and of Patrun: called, or made with new, with the options or a customizer.

find with collect given as true answers Data[], and otherwise Found | null.

What compiles is not in every case what a function takes when it runs. A subject may be any object to the types, so an array or an instance of a class compiles, and matches nothing. A string compiles neither as a subject nor as a pattern, though find would answer null for it, and list []. An instance of a class with no methods compiles as a pattern, and add throws a TypeError for it: see Maps only.


Explanation: design notes

The two rules

patrun is built around two rules and nothing else:

  1. More specific matches win. "More specific" means more matched key/value pairs, not insertion order.
  2. Property names are compared in alphabetical order. This decides between matches with the same number of pairs. When the names are the same, a match on an exact value comes before a match on a *.

Rule 2 is what makes the trie layout independent of how callers build their patterns. add({a:1, b:2}) and add({b:2, a:1}) produce the exact same internal structure.

The order option puts the names you choose before the others in that order. Any one fixed order of names does what rule 2 needs. The option picks one where some names matter more than their spelling says.

Together the rules put the patterns that match a subject in one order, with no ties, so find has one answer and it never depends on the order of adding. spec/ proves this for exact values and the *. See Know which pattern wins when several match.

Why a trie?

A linear scan of N patterns is O(N) per lookup. In the trie, find follows only the branches that the subject matches. When one pattern accounts for all of the subject's keys, that is O(K) in the number of distinct keys in that pattern. When several patterns match the same subject, find visits each of them to compare their sizes, and stops as soon as no remaining branch could match more pairs. For workloads with many patterns sharing a common prefix — Seneca's plugin actions are the canonical example — this is a significant win.

Skip paths

When a pattern omits a key that a sibling pattern includes, add builds a s ("skip") branch that the lookup falls back to. This is what lets {a:1} still match {a:1, b:9} even though b is registered elsewhere — without it, more-specific matches would shadow wider matches incorrectly. (It has nothing to do with the pattern value '*', which is stored in the tree as a value.)

find follows the skip branch as well as the matching value, and keeps the match with more pairs. So a short pattern on an early key does not hide a longer pattern on later keys.

Strings everywhere

Values are stored as strings. A pattern's value is a string, a number or a boolean, and a number or a boolean is stored as the text that JavaScript gives it: 1.0 as '1', and 1e21 as '1e+21'. This keeps the matching logic simple and avoids surprises around == vs === / type coercion. Any other value in a pattern is refused, except null and undefined, whose keys are left out. For ranges of numbers, turn on the interval matcher: see Match numbers by interval.

Only a string, a number or a boolean in a subject can match. A number or a boolean matches as the string it converts to, so { a: 1 } matches the pattern { a: '1' }. Any other value, such as null, an object or an array, matches nothing, not even a *: for matching, the subject has no value there.

Keys and values that name members of Object.prototype, such as __proto__, constructor or toString, are strings like any other. They are stored inside the matcher only, so adding them cannot change other objects. A subject has such a key only if it sets it.

Maps only

A pattern is a map, and so is a subject. In JavaScript that is an object written as a literal, such as { a: 1 } or what JSON.parse returns, or an object with no prototype, made with Object.create(null). Nothing else is one: not null, not an array, a string, a number or a function, and not an instance of a class, a Map among them.

Only what a map holds itself is part of it. A pattern's pairs are the keys that Object.keys lists. A subject has a value for a key when the key is its own, and the value is a string, a number or a boolean. Nothing that an object inherits counts.

The empty string is not a key. No pattern can have it.

What happens to anything else depends on what was asked:

  • add and remove, which change the matcher, throw a TypeError and change nothing. They do the same for a pattern with a value that is not a string, a number or a boolean.
  • find and findexact answer null, and collect answers []. Nothing matches a subject that is not a map, not even the empty pattern {}.
  • list answers [], as no pattern has the pairs of such a partial pattern. list() and list(null) still list everything: there is no partial pattern then.

A subject may have the empty string as a key. No pattern asks for it, so find passes over it, and findexact finds nothing, as no pattern has every key of that subject.

A subject must give the same value each time one of its keys is read. find may read a key more than once, so a getter, or a Proxy, that answers differently each time has no defined match.

const pm = patrun().add({}, 'ROOT').add({ length: 3 }, 'LEN3')

pm.add(null, 'X')        // throws TypeError
pm.add({ '': 1 }, 'X')   // throws TypeError
pm.find('abc')           // → null
pm.find([1, 2, 3])       // → null
pm.find({ length: 3 })   // → 'LEN3'
pm.find({})              // → 'ROOT'

Inside, nothing that the matcher keeps inherits from Object.prototype: not the nodes of its tree, nor its maps of values, nor its matchers' records. So a member that other code adds to Object.prototype is never read as part of the tree. The matcher itself, and what list returns, are ordinary objects.

The definition

spec/ defines what a matcher answers for exact values and the *, in Lean 4: which patterns match, which one find picks, and what findexact, collect and list give. A model computes those answers, with a proof for each operation, and checks the rows that both ports share in test/data/. It also writes test/data/spec.tsv, which both ports run. spec/README.md lists where the ports still differ from it. Run make spec with Lean 4.24.1 installed.

Why not "just write if statements"?

A handful of cases is fine as if statements. But once your dispatch table has sub-cases and sub-sub-cases, the if ladder stops being readable and stops being maintainable — adding a new branch becomes a merge-conflict generator. patrun lets each branch be added (and removed, listed, inspected) independently.


Releasing

Releases are made by the Publish workflow, run by hand from the Actions tab. It publishes the npm package with npm trusted publishing (GitHub OIDC), so no npm token is stored anywhere, and tags the Go module. The comments at the top of the workflow say how to run it and what npmjs.com must be told once.

What each release changed is in CHANGELOG.md for the npm package and go/CHANGELOG.md for the Go module. The workflow gives each GitHub release what its changelog says under the heading of the version, so write that section before releasing.

License

Copyright (c) 2013-2025, Richard Rodger and other contributors. Licensed under MIT.

Keywords