Skip to content

knotkit/trie

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

import {
function uncompressedSegmentedTrie<V>(entries?: Iterable<SegmentedTrieEntry<V>>): SegmentedTrie<V>

Create a

SegmentedTrie

backed by one node per distinct segment prefix, each holding its children in a Map keyed by the next segment.

Shared key prefixes are stored once and looked up once, which is what turns longest-prefix resolution into a single top-down walk. Prefer

compressedSegmentedTrie

when keys are deep or mostly non-branching, which is when packing segment runs into edge labels pays for its split bookkeeping; prefer a plain Map<string, V> keyed on the joined string when only exact matches are needed.

@param ― entries - Key-value pairs to store, in iteration order. A repeated key overwrites the earlier value, mirroring Map, and entries before an invalid one stay stored.

@throws ― {TrieInvalidInputError} When an entry key is not an array of strings.

uncompressedSegmentedTrie
} from 'knotkit/trie'
const
const catalog: SegmentedTrie<number>
catalog
=
uncompressedSegmentedTrie<number>(entries?: Iterable<SegmentedTrieEntry<number>> | undefined): SegmentedTrie<number>

Create a

SegmentedTrie

backed by one node per distinct segment prefix, each holding its children in a Map keyed by the next segment.

Shared key prefixes are stored once and looked up once, which is what turns longest-prefix resolution into a single top-down walk. Prefer

compressedSegmentedTrie

when keys are deep or mostly non-branching, which is when packing segment runs into edge labels pays for its split bookkeeping; prefer a plain Map<string, V> keyed on the joined string when only exact matches are needed.

@param ― entries - Key-value pairs to store, in iteration order. A repeated key overwrites the earlier value, mirroring Map, and entries before an invalid one stay stored.

@throws ― {TrieInvalidInputError} When an entry key is not an array of strings.

uncompressedSegmentedTrie
(
['google', 'google_analytics', 'zoho', 'zoho_crm', 'internal_search'].
Array<string>.map<{
segments: string[];
value: number;
}>(callbackfn: (value: string, index: number, array: string[]) => {
segments: string[];
value: number;
}, thisArg?: any): {
segments: string[];
value: number;
}[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
slug: string
slug
,
index: number
index
) => ({
segments: string[]
segments
:
slug: string
slug
.
String.split(separator: string | RegExp, limit?: number): string[] (+1 overload)

Split a string into substrings using the specified separator and return them as an array.

@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

@param ― limit A value used to limit the number of elements returned in the array.

split
('_'),
value: number
value
:
index: number
index
,
})),
)
const catalog: SegmentedTrie<number>
catalog
.
SegmentedTrie<number>.longestPrefix: (segments: SegmentedKey) => SegmentedTrieEntry<number> | undefined

Resolve the longest stored key that is a segment-wise prefix of the query, including the query itself and the empty key. O(m) expected.

The walk stops at the first missing segment, because no deeper key can prefix the query. Returns the matched key as a fresh prefix of the query array together with its value, or undefined when no stored key prefixes the query.

longestPrefix
('GOOGLE_ANALYTICS_RUN_REPORT'.
String.toLowerCase(): string

Converts all the alphabetic characters in a string to lowercase.

toLowerCase
().
String.split(separator: string | RegExp, limit?: number): string[] (+1 overload)

Split a string into substrings using the specified separator and return them as an array.

@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

@param ― limit A value used to limit the number of elements returned in the array.

split
('_'))
// { segments: ['google', 'analytics'], value: 1 } (longest stored prefix wins)
const catalog: SegmentedTrie<number>
catalog
.
SegmentedTrie<number>.longestPrefix: (segments: SegmentedKey) => SegmentedTrieEntry<number> | undefined

Resolve the longest stored key that is a segment-wise prefix of the query, including the query itself and the empty key. O(m) expected.

The walk stops at the first missing segment, because no deeper key can prefix the query. Returns the matched key as a fresh prefix of the query array together with its value, or undefined when no stored key prefixes the query.

longestPrefix
(['zoho', 'sheets', 'read'])
// { segments: ['zoho'], value: 2 }
const catalog: SegmentedTrie<number>
catalog
.
SegmentedTrie<number>.longestPrefix: (segments: SegmentedKey) => SegmentedTrieEntry<number> | undefined

Resolve the longest stored key that is a segment-wise prefix of the query, including the query itself and the empty key. O(m) expected.

The walk stops at the first missing segment, because no deeper key can prefix the query. Returns the matched key as a fresh prefix of the query array together with its value, or undefined when no stored key prefixes the query.

longestPrefix
(['zillow', 'list'])
// undefined — no stored key prefixes the query
trie.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' }
  • 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
FactoryChoose whenCost
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 splitsone 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 pathsone 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

{"v":1,"box":[58.7743,94.1597,913.7333,437.3555],"x":{"s":"linear","lim":[0.325,16.675],"inv":false,"g":0,"t":"Unbranched suffix length (segments)","tk":[[1,"1"],[4,"4"],[8,"8"],[12,"12"],[16,"16"]]},"y":{"s":"linear","lim":[10.96,569.04],"inv":false,"g":0,"tk":[[34,"34"],[162,"162"],[290,"290"],[418,"418"],[546,"546"]]},"ti":"Compressed stays at 34 nodes; uncompressed adds 32 per segment, 16× at depth 16","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,66,2,98,4,162,6,226,8,290,12,418,16,546],"p":[94.07,403.51,146.36,383.83,250.94,344.47,355.53,305.11,460.11,265.76,669.27,187.04,878.44,108.33]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,66,2,98,4,162,6,226,8,290,12,418,16,546],"p":[94.07,403.51,146.36,383.83,250.94,344.47,355.53,305.11,460.11,265.76,669.27,187.04,878.44,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[1,34,2,34,4,34,6,34,8,34,12,34,16,34],"p":[94.07,423.19,146.36,423.19,250.94,423.19,355.53,423.19,460.11,423.19,669.27,423.19,878.44,423.19]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,34,2,34,4,34,6,34,8,34,12,34,16,34],"p":[94.07,423.19,146.36,423.19,250.94,423.19,355.53,423.19,460.11,423.19,669.27,423.19,878.44,423.19]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 1 4 8 12 16 Unbranched suffix length (segments) 34 162 290 418 546 Nodes each layout allocates for 32 routes, counted by its rule Uncompressed Compressed Compressed stays at 34 nodes; uncompressed adds 32 per segment, 16× at depth 16
{"v":1,"box":[58.7743,150.6246,465.7333,437.3555],"x":{"s":"linear","lim":[0.325,16.675],"inv":false,"g":0,"t":"Unbranched suffix length (segments)","tk":[[1,"1"],[4,"4"],[8,"8"],[12,"12"],[16,"16"]]},"y":{"s":"linear","lim":[10.96,569.04],"inv":false,"g":0,"tk":[[34,"34"],[162,"162"],[290,"290"],[418,"418"],[546,"546"]]},"ti":"Compressed stays at 34 nodes;\nuncompressed adds 32 per segment, 16× at\ndepth 16","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,66,2,98,4,162,6,226,8,290,12,418,16,546],"p":[75.58,409.08,100.47,392.64,150.25,359.75,200.03,326.87,249.81,293.99,349.37,228.23,448.93,162.46]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,66,2,98,4,162,6,226,8,290,12,418,16,546],"p":[75.58,409.08,100.47,392.64,150.25,359.75,200.03,326.87,249.81,293.99,349.37,228.23,448.93,162.46]},{"k":"line","c":"#fffff8","s":"x","d":[1,34,2,34,4,34,6,34,8,34,12,34,16,34],"p":[75.58,425.52,100.47,425.52,150.25,425.52,200.03,425.52,249.81,425.52,349.37,425.52,448.93,425.52]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,34,2,34,4,34,6,34,8,34,12,34,16,34],"p":[75.58,425.52,100.47,425.52,150.25,425.52,200.03,425.52,249.81,425.52,349.37,425.52,448.93,425.52]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 1 4 8 12 16 Unbranched suffix length (segments) 34 162 290 418 546 Nodes each layout allocates for 32 routes, counted by its rule Uncompressed Compressed Compressed stays at 34 nodes; uncompressed adds 32 per segment, 16× at depth 16
  • 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 against knotkit/trie in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
uncompressedSegmentedTrieSegmentedTrie<V>Segment trie with one node per segment, each node holding a `Map` of children in insertion order.
compressedSegmentedTrieSegmentedTrie<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
MemberCost
sizeO(1)
hasO(m) expected
getO(m) expected
setO(m) expected
deleteO(m) expected
longestPrefixO(m) expected
keysO(k) total
entriesO(k) total
compressedSegmentedTrie 8 members
MemberCost
sizeO(1)
hasO(m) expected
getO(m) expected
setO(m) expected
deleteO(m) expected
longestPrefixO(m) expected
keysO(k) total
entriesO(k) total
InputTypeGet one from
value encoding for a binary artifact, which no artifact carries backElementCodec<V>knotkit/wire
value validation for a JSON artifact, whose projection carries no value types(value: unknown) => value is Vthe caller
key segmentation, including the delimiter and any case or Unicode normalization, which the trie never performs(query: string) => readonly string[]the caller

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

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
If you need to…Use instead
look up a value by an exact key only, never by a prefixMap
decide the delimiter, or normalize case and Unicode before matchingString.prototype.split and String.prototype.toLowerCase before building or querying keys
match a string against wildcards, character classes, or a rangeRegExp
iterate stored keys in sorted orderArray.prototype.sort over Map.keys()
enumerate stored string keys that begin with a query prefixknotkit/prefix-index
find keys sharing a suffix, or containing a substringa scan over Map.keys() with String.prototype.includes, or a suffix automaton

Measured by the suite in 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.

Prompt · knotkit/trie
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/