# knotkit/trie

> Resolves delimiter-separated token keys by longest prefix in a single walk

## Use

```ts
import { uncompressedSegmentedTrie } from 'knotkit/trie'

const catalog = uncompressedSegmentedTrie(
  ['google', 'google_analytics', 'zoho', 'zoho_crm', 'internal_search'].map((slug, index) => ({
    segments: slug.split('_'),
    value: index,
  })),
)

catalog.longestPrefix('GOOGLE_ANALYTICS_RUN_REPORT'.toLowerCase().split('_'))
// { segments: ['google', 'analytics'], value: 1 } (longest stored prefix wins)
catalog.longestPrefix(['zoho', 'sheets', 'read'])
// { segments: ['zoho'], value: 2 }
catalog.longestPrefix(['zillow', 'list'])
// undefined — no stored key prefixes the query
```

```ts
const regions = uncompressedSegmentedTrie<string>([
  { segments: ['eu', 'west', '1'], value: 'eu-west-1' },
  { segments: [], value: 'us-east-1' },
])

regions.longestPrefix(['eu', 'west', '1', 'a']) // { segments: ['eu', 'west', '1'], value: 'eu-west-1' }
regions.longestPrefix(['ap', 'south', '1']) // { segments: [], value: 'us-east-1' }
```

## What it solves

* find the longest known key that prefixes a query, such as a tool slug or a route segment
* resolve a dotted path, package name, or header name against a catalog built once
* fall back from a specific entry to a broader one, including an empty default key
* look up a known set of token sequences by prefix without slicing and re-joining candidates

## Choose a layout

| Factory                                        | Choose when                                                                                                                                                                                               | Cost                                                                                                                                         |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `uncompressedSegmentedTrie`kind `uncompressed` | keys average four segments or fewer and most segments are keys themselves, so compression removes under 12% of nodes and only adds edge splits                                                            | one Map lookup per segment; 126,343 nodes against 111,987 for the compressed layout on 100,000 underscore slugs of 1-4 segments              |
| `compressedSegmentedTrie`kind `compressed`     | keys average more than four segments and most of them do not branch, where node count falls around 7x and deep misses resolve in 9.78-13.19 ms against 13.19-16.71 ms uncompressed at 100,000 slash paths | one Map lookup per edge plus a segment-by-segment comparison of the skipped label, and an edge split on any insert that lands inside an edge |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/trie/README.md#performance)

## Worked example

Routes3232Reset

* Routes for the extended path (uncompressed / compressed): handler-0 / handler-0.
* One node per route suffices after compressing its unbranched suffix.
* At depth 16, serialized bytes (uncompressed / compressed): 3232 / 3232.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/trie/demo.ts) against `knotkit/trie` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                      | Returns            | Does                                                                                                                     |
| ------------------------------------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| [`uncompressedSegmentedTrie`](/reference/knotkit/trie/functions/uncompressedsegmentedtrie/) | `SegmentedTrie<V>` | Segment trie with one node per segment, each node holding a \`Map\` of children in insertion order.                      |
| [`compressedSegmentedTrie`](/reference/knotkit/trie/functions/compressedsegmentedtrie/)     | `SegmentedTrie<V>` | Radix-compressed segment trie: one node per branch point or key end, with the skipped segments carried as an edge label. |

Cost per member. Open a row for every operation.

`uncompressedSegmentedTrie` 8 members

| Member          | Cost          |
| --------------- | ------------- |
| `size`          | O(1)          |
| `has`           | O(m) expected |
| `get`           | O(m) expected |
| `set`           | O(m) expected |
| `delete`        | O(m) expected |
| `longestPrefix` | O(m) expected |
| `keys`          | O(k) total    |
| `entries`       | O(k) total    |

`compressedSegmentedTrie` 8 members

| Member          | Cost          |
| --------------- | ------------- |
| `size`          | O(1)          |
| `has`           | O(m) expected |
| `get`           | O(m) expected |
| `set`           | O(m) expected |
| `delete`        | O(m) expected |
| `longestPrefix` | O(m) expected |
| `keys`          | O(k) total    |
| `entries`       | O(k) total    |

## What you pass in

| Input                                                                                                          | Type                                   | Get one from                     |
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------- | -------------------------------- |
| value encoding for a binary artifact, which no artifact carries back                                           | `ElementCodec<V>`                      | [`knotkit/wire`](/modules/wire/) |
| value validation for a JSON artifact, whose projection carries no value types                                  | `(value: unknown) => value is V`       | `the caller`                     |
| key segmentation, including the delimiter and any case or Unicode normalization, which the trie never performs | `(query: string) => readonly string[]` | `the caller`                     |

## Errors

Every error this module throws is `TrieInvalidInputError` or `TrieParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `TrieInvalidInputError`

  `INVALID_KEY` `INVALID_SEGMENT`

* `TrieParseError`

  `FOREIGN_STRUCTURE` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_ENTRIES` `INVALID_ENTRY` `INVALID_VALUE` `DUPLICATE_KEY` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `INVALID_PACKAGE_HEADER`

## Save and restore

Serialization lives in a separate entrypoint, `knotkit/trie/wire`, so code that never saves a structure never loads a parser.

* Functions

  `serializeSegmentedTrie`, `deserializeSegmentedTrie`, `serializeSegmentedTrieJson`, `deserializeSegmentedTrieJson`

* Formats

  binary, json

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                     | Use instead                                                                              |
| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| look up a value by an exact key only, never by a prefix             | Map                                                                                      |
| decide the delimiter, or normalize case and Unicode before matching | String.prototype.split and String.prototype.toLowerCase before building or querying keys |
| match a string against wildcards, character classes, or a range     | RegExp                                                                                   |
| iterate stored keys in sorted order                                 | Array.prototype.sort over Map.keys()                                                     |
| enumerate stored string keys that begin with a query prefix         | [`knotkit/prefix-index`](/modules/prefix-index/)                                         |
| find keys sharing a suffix, or containing a substring               | a scan over Map.keys() with String.prototype.includes, or a suffix automaton             |

## Performance

Measured by the suite in [`packages/trie/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/trie/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#segmented-trie).

## Prompt an agent

Prompt · knotkit/trieCopy prompt

```
Use knotkit/trie for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/trie'.

Exports:
- `uncompressedSegmentedTrie` → `SegmentedTrie<V>`: Segment trie with one node per segment, each node holding a `Map` of children in insertion order.
- `compressedSegmentedTrie` → `SegmentedTrie<V>`: Radix-compressed segment trie: one node per branch point or key end, with the skipped segments carried as an edge label.

Pick the layout by these rules:
- `uncompressedSegmentedTrie` (kind 'uncompressed') when keys average four segments or fewer and most segments are keys themselves, so compression removes under 12% of nodes and only adds edge splits
- `compressedSegmentedTrie` (kind 'compressed') when keys average more than four segments and most of them do not branch, where node count falls around 7x and deep misses resolve in 9.78-13.19 ms against 13.19-16.71 ms uncompressed at 100,000 slash paths

Inputs and their sources:
- value encoding for a binary artifact, which no artifact carries back: `ElementCodec<V>` from `knotkit/wire`
- value validation for a JSON artifact, whose projection carries no value types: `(value: unknown) => value is V` from `the caller`
- key segmentation, including the delimiter and any case or Unicode normalization, which the trie never performs: `(query: string) => readonly string[]` from `the caller`

Use something else when:
- look up a value by an exact key only, never by a prefix → Map
- decide the delimiter, or normalize case and Unicode before matching → String.prototype.split and String.prototype.toLowerCase before building or querying keys
- match a string against wildcards, character classes, or a range → RegExp
- iterate stored keys in sorted order → Array.prototype.sort over Map.keys()
- enumerate stored string keys that begin with a query prefix → knotkit/prefix-index
- find keys sharing a suffix, or containing a substring → a scan over Map.keys() with String.prototype.includes, or a suffix automaton

Errors are TrieInvalidInputError or TrieParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/trie/wire` (serializeSegmentedTrie, deserializeSegmentedTrie, serializeSegmentedTrieJson, deserializeSegmentedTrieJson).

Full page: https://knotkit.jkomyno.dev/modules/trie.md
Types: node_modules/knotkit/trie/ and https://knotkit.jkomyno.dev/reference/knotkit/trie/
```

## See also

* [API reference](/reference/knotkit/trie/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/trie/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/trie/knotkit.capability.json)suggest a change to the source record
