# knotkit/prefix-index

> Enumerates a bounded number of distinct strings that start with a prefix in UTF-16 order

## Use

```ts
import { prefixIndex } from 'knotkit/prefix-index'

const commands = prefixIndex(['cache', 'compile', 'cat', 'cache', 'copy'])
Array.from(commands.keysWithPrefix('ca', 2)) // ['cache', 'cat']
Array.from(commands.keysWithPrefix('co', 1)) // ['compile']
```

```ts
import { prefixIndex } from 'knotkit/prefix-index'
import { termIndex } from 'knotkit/term-index'

const docs = [
  ['cache', 'setup'],
  ['caching', 'rules'],
  ['queue', 'setup'],
]
const index = termIndex(docs, (tokens) => tokens)
const vocabulary = prefixIndex(index.keys())

const terms = Array.from(vocabulary.keysWithPrefix('cac', 8))
const hits = index.search(terms, { limit: 5 })
```

## What it solves

* fetch up to a fixed number of autocomplete candidates from a static vocabulary
* expand the last query token into matching terms before an exact posting query
* list identifiers or paths starting with a string without scanning all keys

## Worked example

* 2,048 generated help titles.
* 16 terms start with “con”.
* Full scan → 768 matching articles.
* Term cap 1 → 32 articles (4.2% of full scan)
* Suggestions → concurrency
* Example → Concurrency reference on Linux
* Term cap 4 → 192 articles (25% of full scan)
* Suggestions → concurrency, config, configuration, configure
* Example → Configure reference on Linux
* Term cap 8 → 384 articles (50% of full scan)
* Suggestions → concurrency, config, …, console
* Example → Console reference on Linux

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/prefix-index/demo.ts) against `knotkit/prefix-index`.

## API

| Export                                                                  | Returns       | Does                                                                                                  |
| ----------------------------------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------- |
| [`prefixIndex`](/reference/knotkit/prefix-index/functions/prefixindex/) | `PrefixIndex` | Snapshot distinct strings and enumerate at most the requested number of keys beginning with a prefix. |

Cost per member. Open a row for every operation.

`prefixIndex` 4 members

| Member           | Cost                                                                                                |
| ---------------- | --------------------------------------------------------------------------------------------------- |
| `build`          | O(n) expected set operations for n input keys, plus O(u log(u + 1)) comparisons for u distinct keys |
| `size`           | O(1)                                                                                                |
| `keys`           | O(1) per key                                                                                        |
| `keysWithPrefix` | O(log(u + 1) + k) string comparisons for k returned keys, with O(1) extra space                     |

## What you pass in

| Input                | Type               | Get one from |
| -------------------- | ------------------ | ------------ |
| string keys to index | `Iterable<string>` | `the caller` |

## Errors

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

* `INVALID_LIMIT`

## When not to use it

| If you need to…                                               | Use instead                                    |
| ------------------------------------------------------------- | ---------------------------------------------- |
| find a stored delimiter-separated key that prefixes the query | [`knotkit/trie`](/modules/trie/)               |
| update keys between ordered range queries                     | [`knotkit/ordered-map`](/modules/ordered-map/) |
| rank documents after expanding the query                      | [`knotkit/term-index`](/modules/term-index/)   |

## Performance

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

## Prompt an agent

Prompt · knotkit/prefix-indexCopy prompt

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

Exports:
- `prefixIndex` → `PrefixIndex`: Snapshot distinct strings and enumerate at most the requested number of keys beginning with a prefix.

Inputs and their sources:
- string keys to index: `Iterable<string>` from `the caller`

Use something else when:
- find a stored delimiter-separated key that prefixes the query → knotkit/trie
- update keys between ordered range queries → knotkit/ordered-map
- rank documents after expanding the query → knotkit/term-index

Errors are PrefixIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

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

## See also

* [API reference](/reference/knotkit/prefix-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/prefix-index/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/prefix-index/knotkit.capability.json)suggest a change to the source record
