Pick the most specific match
Add a general pattern and its special cases, and let find answer with the most specific one that matches.
Use this when some queries need a different answer from the rest: add the general pattern, then a more specific pattern for each special case. find gives the data of the pattern that matches the most of the query's properties.
const patrun = require('patrun')
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
The number of properties comes first. A pattern with more of them wins even when its keys come later in the alphabet:
const patrun = require('patrun')
const pm = patrun()
.add({ a: 1 }, 'A')
.add({ b: 2, c: 3 }, 'BC')
pm.find({ a: 1, b: 2, c: 3 }) // → 'BC' two properties beat one
pm.find({ a: 1, b: 2 }) // → 'A' only { a: 1 } matches
In Go #
pm := patrun.New()
pm.Add(map[string]string{"a": "1"}, s("A"))
pm.Add(map[string]string{"a": "1", "b": "1"}, s("AB"))
pm.Add(map[string]string{"b": "2", "c": "3"}, s("BC"))
pm.Find(map[string]string{"a": "1", "b": "1"}) // → "AB"
pm.Find(map[string]string{"a": "1", "b": "9"}) // → "A"
pm.Find(map[string]string{"a": "1", "b": "2", "c": "3"}) // → "BC"
What to watch for #
When two patterns that match a query have as many properties as each other, the first property where they differ decides between them, not the order of adding. Their keys are compared in alphabetical order, and at the same key an exact value beats a star. If that order gives the wrong answer for a query that matches both, add a pattern for the two together, which has more properties and so wins:
const patrun = require('patrun')
const pm = patrun().add({ a: 1 }, 'A').add({ b: 2 }, 'B')
pm.find({ a: 1, b: 2 }) // → 'A'
pm.add({ a: 1, b: 2 }, 'A-AND-B')
pm.find({ a: 1, b: 2 }) // → 'A-AND-B'
To put some keys before the others, see Choose which keys come first. Every rule that orders the matches is in How a match is chosen.