Collect every match
Get the data of every pattern that matches a query, in the router's key order, with collect and collectExact.
Use this when every pattern that applies to a query matters, not only the most specific one, as when each adds a layer of settings. collect gives the data of every pattern that matches. A pattern comes before every pattern that begins with its properties, so a general pattern comes before the special cases that begin with it.
const patrun = require('patrun')
const pm = patrun()
.add({}, 'ROOT')
.add({ a: 1 }, 'A')
.add({ a: 1, b: 1 }, 'AB')
.add({ a: '*', b: 1 }, 'SB')
pm.collect({ a: 1, b: 1 }) // → ['ROOT', 'A', 'AB', 'SB']
collectExact gives only the patterns that have every key of the query, in the order find would choose them. The first is what findExact gives:
pm.collectExact({ a: 1, b: 1 }) // → ['AB', 'SB']
find(query, false, true) and find(query, true, true) do the same as the two.
In Go #
pm := patrun.New()
pm.Add(map[string]string{}, s("ROOT"))
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{"a": "*", "b": "1"}, s("SB"))
pm.Collect(map[string]string{"a": "1", "b": "1"}) // → ["ROOT", "A", "AB", "SB"]
pm.CollectExact(map[string]string{"a": "1", "b": "1"}) // → ["AB", "SB"]
What to watch for #
No match gives an empty list, never null. The order is that of the router's keys, not of adding, and it is not from the fewest properties to the most. A pattern comes before one that has all its properties and more only when the other begins with its properties. Here the pattern for Cork in Ireland comes before the one for Ireland, because city comes before country:
const patrun = require('patrun')
const plain = patrun()
.add({}, 'DEFAULT')
.add({ country: 'IE' }, 'IE')
.add({ country: 'IE', city: 'Cork' }, 'IE-CORK')
plain.collect({ country: 'IE', city: 'Cork' }) // → ['DEFAULT', 'IE-CORK', 'IE']
To layer settings from the general to the special, name the keys of the hierarchy in the order option, the most general first. The pattern for a country then begins the pattern for each of its cities:
const pm = patrun({ order: ['country', 'city'] })
.add({}, 'DEFAULT')
.add({ country: 'IE' }, 'IE')
.add({ country: 'IE', city: 'Cork' }, 'IE-CORK')
pm.collect({ country: 'IE', city: 'Cork' }) // → ['DEFAULT', 'IE', 'IE-CORK']
The full order is in How a match is chosen.