# How the tree finds a match

How a router stores its patterns as a tree of keys and values, why a lookup follows only the branches a query matches, and what the skip paths are for.

A router does not check each pattern in turn. It stores its patterns in a tree, and a lookup follows only the branches the query matches.

## The tree

Each level of the tree is one key, in the router's key order. A node holds the key, and a branch for each value a pattern has for it. A pattern is stored by walking down from the root: at each key the pattern has, the walk takes the branch for its value, and the pattern's data is stored at the node where its keys run out.

So the patterns `{ a: 1 }` and `{ a: 1, b: 2 }` share the branch for `a` equal to `1`, and the second goes on to the branch for `b` equal to `2`. [`toJSON`](https://rjrodger.github.io/patrun/reference/javascript.html#tojsonindent) writes the tree out, with each node's key as `k` and its branches as `v`.

## Why a tree

A scan of N patterns takes N comparisons for each lookup. In the tree, a lookup follows only the branches whose values the query has. When one pattern accounts for all of the query's keys, the lookup takes as many steps as that pattern has keys, however many other patterns the router holds. When several patterns match, the lookup visits each of them to compare them, and stops as soon as no branch left could match more properties.

Seneca's actions are the case the tree was built for: many patterns that share their first keys, such as a `role`, and differ in a `cmd`. The lookup goes down the shared branch once.

## Skip paths

A pattern that has no value for a key still has to be found by a query that has one. `{ a: 1 }` must match `{ a: 1, b: 9 }`, though `b` is a level of the tree because another pattern has it. So where a pattern leaves out a key that other patterns have, `add` stores it along a skip path, `s` in the tree's JSON, that passes over that key.

A lookup follows the skip path as well as the branch for the query's value, and keeps the match with more properties. A short pattern on an early key does not hide a longer pattern on later keys.

The star, `'*'`, is not a skip path. It is a value, stored as a branch like any other, and it needs the query to have the key.

## Globs and intervals

An exact value is found in a node's branches by a lookup. A glob or an interval cannot be: whether it matches depends on the query's value. So a node keeps them apart, as `g` in the tree's JSON, in the order they rank, and a lookup tests the query's value against each of them in turn. That is slower than a lookup, so a router with many globs for one key does more work for each query than one with many exact values.
