This is the full developer documentation for Knotkit
# Getting started
> Run your first example in the browser or build the package for your own project.
## Try it in the browser
[Section titled “Try it in the browser”](#try-it-in-the-browser)
Open [Change the priority of queued work](/guides/reprioritize/) and click **Run**. The queue moves the layout task to the front when its priority changes, then returns it first.
## Install from source
[Section titled “Install from source”](#install-from-source)
Knotkit is preparing its first npm release. To use it in your project today, build a package tarball from a checkout. You’ll need Bun to build it and npm to pack it.
```bash
git clone https://github.com/jkomyno/knotkit.git
cd knotkit
bun install --frozen-lockfile
bun run build
npm pack ./packages
```
In your project, install the tarball using its absolute path. Use the filename printed by `npm pack`.
```bash
npm install /path/to/knotkit/knotkit-0.1.0.tgz
```
Knotkit is ESM only. With TypeScript, use 5.x or later and set `moduleResolution` to `"bundler"` or `"nodenext"`.
* Node.js
Node.js 22.12 or later.
* Bun
Supported, and tested in CI.
* Browsers
Browsers with ES2024 support. Import the same module in your browser bundle and on the server.
## Import one module
[Section titled “Import one module”](#import-one-module)
Import the capability you need directly from a subpath such as `knotkit/heap`, `knotkit/bitset`, or `knotkit/sampling`. Your bundler can start from that subpath and include its dependencies.
```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'
const heap = minBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 1
heap.pop() // 1
heap.size // 3
```
`minBinaryHeap` creates a heap, and `numberOrder` tells it how to compare numbers. Orderings, random sources, and hash functions are inputs to the operations that need them, so you can replay a workload with the same inputs.
Not sure which module you need?
[Choose a module](/choosing/) lists every task the modules solve. Search it for what you are trying to do.
## Handle errors
[Section titled “Handle errors”](#handle-errors)
Use the exported error class and its `code` to handle a specific failure. Calling `pop()` on an empty heap raises `HeapInvalidInputError` with the code `EMPTY`.
```ts
import { HeapInvalidInputError, minBinaryHeap, numberOrder } from 'knotkit/heap'
const empty = minBinaryHeap(numberOrder)
try {
empty.pop()
} catch (error) {
if (!(error instanceof HeapInvalidInputError) || error.code !== 'EMPTY') {
throw error
}
// Handle the empty heap.
}
```
Each module page lists its error codes. [Conventions](/conventions/) covers errors, layouts, and seeding in one place.
## Set up your coding agent
[Section titled “Set up your coding agent”](#set-up-your-coding-agent)
Paste this into Claude Code, Cursor, Codex, or any agent that can run commands:
Prompt · set up KnotkitCopy prompt
```
Set up Knotkit in this project.
1. Follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source to build and install the package. Use "bundler" or "nodenext" module resolution in TypeScript.
2. Run `npx skills add jkomyno/knotkit --skill knotkit-select` to install the skill that picks a module for a task.
3. Add this to AGENTS.md (or CLAUDE.md):
Knotkit: pick a module from node_modules/knotkit/capabilities.json, then read node_modules/knotkit//README.md. Import from 'knotkit/'; there is no root import. Create structures with the exported factory functions, branch on error.code, and pass seeds and orderings explicitly.
If something is unclear, read https://knotkit.jkomyno.dev/llms.txt.
```
## Where to go next
[Section titled “Where to go next”](#where-to-go-next)
* [Choose a module](/choosing/) when you know the task and want to find the right data structure.
* [Run a guide](/guides/) for a small example you can adapt to your project.
* [Read the module reference](/modules/) for operation costs, layout choices, and API signatures.
# Choose a module
> Every task the modules solve, in plain words. Search for yours, then open the module that answers it.
Each module page also lists what it is **not** for, and where to go instead, including when a built-in `Map`, `Set`, or array is the better answer.
Describe the task: “top k”, “dedupe ids”, “p-value”… (153 tasks)
## Collections
* filter membership over millions of non-negative integer ids without paying a byte per possible id[bitset](/modules/bitset/)
* combine two id sets by union, intersection, or difference without allocating a third set[bitset](/modules/bitset/)
* ask how many ids are at or below a value or inside a range, which id is the k-th smallest, or which id comes next or before[bitset](/modules/bitset/)
* walk a set of ids in ascending order without sorting them[bitset](/modules/bitset/)
* hold ids scattered across a wide range, such as row or document ids, without allocating the whole range[bitset](/modules/bitset/)
* keep the results of repeated lookups in memory without letting them grow past a fixed size[cache](/modules/cache/)
* bound a store by total byte size or cost instead of by number of entries[cache](/modules/cache/)
* let stored results expire after a fixed time while the clock stays under test control[cache](/modules/cache/)
* find out which entries were pushed out to make room, so they can be flushed or logged[cache](/modules/cache/)
* switch the eviction policy for a given traffic shape without changing any call site[cache](/modules/cache/)
* evict in an order of my own, such as by recompute cost or an assigned priority, while the cache keeps handling weights, expiry, and iteration[cache](/modules/cache/)
* take items out in the order they arrived without Array.prototype.shift turning the loop quadratic[deque](/modules/deque/)
* add and remove items at both ends of a sequence, such as a breadth-first and depth-first hybrid[deque](/modules/deque/)
* keep only the last N values of a stream and learn which value just fell out, for a running sum or moving average[deque](/modules/deque/)
* hold a long numeric buffer in eight bytes per value with no per-element allocation[deque](/modules/deque/)
* read the k-th item from either end of a queue without removing anything[deque](/modules/deque/)
* tell whether two items are already connected, while connections keep arriving one at a time[disjoint-set](/modules/disjoint-set/)
* merge two groups of items into one, pair by pair, and count how many groups remain[disjoint-set](/modules/disjoint-set/)
* run Kruskal's minimum spanning tree, or detect a cycle in an undirected graph[disjoint-set](/modules/disjoint-set/)
* group a large collection of items into its connected components[disjoint-set](/modules/disjoint-set/)
* drive percolation, image segmentation, or any equivalence relation that only ever grows by merging[disjoint-set](/modules/disjoint-set/)
* read the exact number of occurrences of a key[frequency-table](/modules/frequency-table/)
* track repeated integer observations as items enter and leave[frequency-table](/modules/frequency-table/)
* sum frequencies between two bounds after updates[frequency-table](/modules/frequency-table/)
* read a median or quantile by its position among all observations[frequency-table](/modules/frequency-table/)
* repeatedly take the smallest or largest item from a changing collection[heap](/modules/heap/)
* run Dijkstra, Prim, or A\* with decrease-key on a keyed queue[heap](/modules/heap/)
* keep a running top-k over a stream, evicting the worst entry as it arrives[heap](/modules/heap/)
* schedule tasks by priority and re-prioritize work that is already queued[heap](/modules/heap/)
* drain a set in sorted order without sorting all of it first[heap](/modules/heap/)
* find which SSTables' \[minKey, maxKey] fence pointers can hold a key on a level-0 read[interval-index](/modules/interval-index/)
* select every table in the next level whose key range overlaps a compaction input[interval-index](/modules/interval-index/)
* find every booking, lease, or time window that covers a moment or overlaps a span[interval-index](/modules/interval-index/)
* keep a set of ranges that are added and removed by id while answering overlap queries[interval-index](/modules/interval-index/)
* match ranges whose endpoints are byte strings, numbers, or any keys with a total order[interval-index](/modules/interval-index/)
* read the k-th smallest key while keys enter and leave[ordered-map](/modules/ordered-map/)
* count keys at or below a bound[ordered-map](/modules/ordered-map/)
* find the nearest stored key at or above, or at or below, a probe[ordered-map](/modules/ordered-map/)
* iterate key-value entries in a sorted range, from a start key onward, or in descending order[ordered-map](/modules/ordered-map/)
* buffer sorted writes in memory before flushing them in key order, as an LSM MemTable does[ordered-map](/modules/ordered-map/)
* limit one client's request weight and tell it the least whole millisecond to wait before retrying[rate-limit](/modules/rate-limit/)
* limit many clients without letting the per-client table grow with every client ever seen[rate-limit](/modules/rate-limit/)
* choose a rate-limit algorithm by the most weight it admits in a trailing window rather than by its name[rate-limit](/modules/rate-limit/)
* combine two limits for one client into one meter a keyed table accepts like a built-in kind[rate-limit](/modules/rate-limit/)
* prove a limiter's worst case and its retry boundary by replaying the same arrival schedules[rate-limit](/modules/rate-limit/)
* read a set as it was at an earlier point, while it keeps changing[snapshot-set](/modules/snapshot-set/)
* answer whether a value was present at a given moment, for an audit trail or a change log[snapshot-set](/modules/snapshot-set/)
* serve MVCC reads: older readers keep their view while a writer mutates[snapshot-set](/modules/snapshot-set/)
* keep an undo stack over membership, or time-travel debug a collection, without cloning it per step[snapshot-set](/modules/snapshot-set/)
* report when each value joined and left a live set, as of any snapshot taken earlier[snapshot-set](/modules/snapshot-set/)
* build the data or index block of a sorted string table from key-value pairs already in key order[sorted-block](/modules/sorted-block/)
* store many sorted Uint8Array keys that share long prefixes in fewer bytes than an array of pairs[sorted-block](/modules/sorted-block/)
* look up, seek to the first key at or above a bound, or scan a key range in a block built once[sorted-block](/modules/sorted-block/)
* persist a sorted run as bytes and reload it with every offset, varint, and key order validated[sorted-block](/modules/sorted-block/)
* trade block size against lookup cost by choosing how often a key is stored whole[sorted-block](/modules/sorted-block/)
* read only the first few items across several already-sorted inputs[sorted-merge](/modules/sorted-merge/)
* merge sorted runs or posting lists with one buffered item per input[sorted-merge](/modules/sorted-merge/)
* combine sorted streams with deterministic ordering for equal items[sorted-merge](/modules/sorted-merge/)
* merge sorted async streams, such as remote SSTable block reads, without buffering whole inputs[sorted-merge](/modules/sorted-merge/)
## Search and text
* look up all records tagged with an exact key after reading the input once[inverted-index](/modules/inverted-index/)
* visit records carrying any requested tag once, in their original order[inverted-index](/modules/inverted-index/)
* group record positions by feature when a record can supply several features or repeat one[inverted-index](/modules/inverted-index/)
* fetch up to a fixed number of autocomplete candidates from a static vocabulary[prefix-index](/modules/prefix-index/)
* expand the last query token into matching terms before an exact posting query[prefix-index](/modules/prefix-index/)
* list identifiers or paths starting with a string without scanning all keys[prefix-index](/modules/prefix-index/)
* rank documents matching any of a set of exact tokens[term-index](/modules/term-index/)
* restrict ranked search to eligible document IDs without changing corpus statistics[term-index](/modules/term-index/)
* read term counts per document and document frequencies without scanning the corpus[term-index](/modules/term-index/)
* find the longest known key that prefixes a query, such as a tool slug or a route segment[trie](/modules/trie/)
* resolve a dotted path, package name, or header name against a catalog built once[trie](/modules/trie/)
* fall back from a specific entry to a broader one, including an empty default key[trie](/modules/trie/)
* look up a known set of token sequences by prefix without slicing and re-joining candidates[trie](/modules/trie/)
## Graphs and optimization
* count permutations or unordered combinations exactly[combinatorics](/modules/combinatorics/)
* compute Stirling numbers for permutations by cycle count and partitions by block count[combinatorics](/modules/combinatorics/)
* compute Bell numbers to count all set partitions[combinatorics](/modules/combinatorics/)
* evaluate log-factorials and log binomial coefficients for large inputs[combinatorics](/modules/combinatorics/)
* share repeated subexpressions even when their operands were built from different equivalent terms[e-graph](/modules/e-graph/)
* recognize that replacing an operand with an equal operand preserves an expression[e-graph](/modules/e-graph/)
* select the cheapest equivalent expression under a caller's operator prices[e-graph](/modules/e-graph/)
* find a good route or schedule where improving one position at a time gets stuck[evolution](/modules/evolution/)
* keep the best candidate seen across generations while a whole population changes[evolution](/modules/evolution/)
* select parents in proportion to rank, then recombine two orderings into one child ordering[evolution](/modules/evolution/)
* run an optimizer deterministically from a seed so a recorded run replays exactly[evolution](/modules/evolution/)
* decide when to stop from a stagnation count instead of a fixed generation budget[evolution](/modules/evolution/)
* mutate or cross a permutation without touching the array the caller handed in[evolution](/modules/evolution/)
* find the fewest-hops route between two points or the cheapest routes to selected destinations, all reachable points, or between every pair on a small graph[graph](/modules/graph/)
* order tasks, builds, or courses so every dependency comes first, or find the cycle that makes that impossible[graph](/modules/graph/)
* count the islands or connected pieces of a map, a grid, or a network, and say which piece each item is in[graph](/modules/graph/)
* decide whether one item can reach another, and list the steps of the path between them[graph](/modules/graph/)
* ask who depends on an item and what it depends on, with in-degree and out-degree[graph](/modules/graph/)
* store a graph from an edge list as compact typed arrays, and persist it as bytes[graph](/modules/graph/)
## Randomness and statistics
* rank vector differences by coordinate magnitude or angle[distance](/modules/distance/)
* measure the extra information cost of approximating one probability distribution with another[distance](/modules/distance/)
* bound how much any event probability can change between two probability distributions[distance](/modules/distance/)
* compute exact set overlap or set distance[distance](/modules/distance/)
* look up which direction to rank a comparison and whether it is symmetric or follows the triangle inequality[distance](/modules/distance/)
* compute probability below a threshold in a named distribution[distribution](/modules/distribution/)
* find a quantile for a distribution[distribution](/modules/distribution/)
* draw values from an injected source according to a distribution[distribution](/modules/distribution/)
* summarize observed numbers with a mean, variance, quantile, histogram, or correlation[distribution](/modules/distribution/)
* compute a chi-square p-value for observed counts against category probabilities[hypothesis-test](/modules/hypothesis-test/)
* test whether draws fit a continuous distribution with Kolmogorov-Smirnov[hypothesis-test](/modules/hypothesis-test/)
* compare the distributions of two samples[hypothesis-test](/modules/hypothesis-test/)
* test one sample mean, two sample means, or paired measurements with a t-test, or three or more group means with a one-way ANOVA, or compare samples by rank with Mann-Whitney U, Wilcoxon signed-rank, or Kruskal-Wallis[hypothesis-test](/modules/hypothesis-test/)
* test an observed success count using an exact binomial p-value[hypothesis-test](/modules/hypothesis-test/)
* calculate a two-sided or directional Fisher exact p-value for a 2-by-2 table[hypothesis-test](/modules/hypothesis-test/)
* replay the same random sequence from a seed in tests, simulations, or procedural generation[prng](/modules/prng/)
* roll an unbiased integer in 1..n without modulo bias[prng](/modules/prng/)
* draw unsigned 64-bit values larger than 2^53 without losing precision or capping the bound[prng](/modules/prng/)
* give parallel workers non-overlapping subsequences of one sequence[prng](/modules/prng/)
* produce the same random values in a browser, in Node.js, and in Bun[prng](/modules/prng/)
* pick k distinct items from a population or an index range without shuffling the whole population[sampling](/modules/sampling/)
* shuffle a copy of a list reproducibly, so a rerun from the same seed yields the same order[sampling](/modules/sampling/)
* pick one item in proportion to its weight, or k items in proportion to their weights without replacement[sampling](/modules/sampling/)
* keep a bounded uniform sample of a stream whose length is not known in advance[sampling](/modules/sampling/)
* pick two distinct items, optionally at least a minimum number of positions apart[sampling](/modules/sampling/)
* replay a simulation or a generated test fixture exactly from a recorded seed[sampling](/modules/sampling/)
* count distinct visitors without storing every visitor[scalar-sketch](/modules/scalar-sketch/)
* check whether an id or URL was already processed, with a small false-positive rate and no false negatives[scalar-sketch](/modules/scalar-sketch/)
* find the heavy hitters of a stream without keeping a counter per key[scalar-sketch](/modules/scalar-sketch/)
* estimate how much two large sets overlap without holding both of them[scalar-sketch](/modules/scalar-sketch/)
* answer those questions per partition and merge the answers afterwards[scalar-sketch](/modules/scalar-sketch/)
* keep the answer in a fixed-size summary that is serialized now and queried later[scalar-sketch](/modules/scalar-sketch/)
* skip a disk or network read for a key that an immutable table or file certainly does not hold[static-filter](/modules/static-filter/)
* check membership in a set of byte keys that is known in full before the first query and never changes[static-filter](/modules/static-filter/)
* keep a membership test for millions of keys in the smallest memory a Worker or browser tab can spare[static-filter](/modules/static-filter/)
* ship a compact membership summary beside an SSTable, a static index, or a release artifact and reload it later[static-filter](/modules/static-filter/)
* pick between a 0.39% and a 0.0015% false-positive rate at 9 to 10 or 18 to 20 bits per key[static-filter](/modules/static-filter/)
## Serialization and utilities
* store the same artifact once no matter how many callers write it[cas](/modules/cas/)
* prove that the bytes a store returned are the content a key names[cas](/modules/cas/)
* share artifacts between processes that do not share a filesystem[cas](/modules/cas/)
* keep serialized structures in an object store, a browser cache, or a Map behind one interface[cas](/modules/cas/)
* catch a failure from any Knotkit package without importing each package's own error classes[errors](/modules/errors/)
* read which package failed, which category, and the exact code from a caught error[errors](/modules/errors/)
* recognize a Knotkit error that crossed a realm or came from a duplicate copy of a package, where instanceof reports a false negative[errors](/modules/errors/)
* format an unknown thrown value into a message without a hostile toString replacing the caller's error[errors](/modules/errors/)
* fail a decode on the first invalid element using the throwing package's own error class and code[errors](/modules/errors/)
* fingerprint bytes, text, or an unsigned integer the same way in every browser, Node.js, and Bun runtime[hash](/modules/hash/)
* shard keys across buckets or deduplicate records by a cheap fingerprint[hash](/modules/hash/)
* hash table keys without allocating or retaining a copy of the input[hash](/modules/hash/)
* reproduce earlier digests in a later process from a persisted algorithm version and seed[hash](/modules/hash/)
* hash a large payload chunk by chunk without holding it all in memory[hash](/modules/hash/)
* build a composite key such as (user id, timestamp) that a byte-ordered store sorts field by field[key-encoding](/modules/key-encoding/)
* sort one field of a composite key descending, such as newest version first, without a custom comparator[key-encoding](/modules/key-encoding/)
* store signed integers or doubles as keys that sort numerically rather than by their raw bytes[key-encoding](/modules/key-encoding/)
* scan every key that starts with a prefix by computing the range's exclusive upper bound[key-encoding](/modules/key-encoding/)
* compare or sort Uint8Array keys in the order memcmp, LevelDB, or IndexedDB uses[key-encoding](/modules/key-encoding/)
* encode a package-identified binary artifact with validated section geometry[wire](/modules/wire/)
* declare a module's binary artifact once so every decoder runs the same prelude and raises the same codes[wire](/modules/wire/)
* encode generic values with an injected byte codec[wire](/modules/wire/)
* prove an element codec injective over a run before emitting an artifact[wire](/modules/wire/)
* share bounded little-endian wire primitives across data-structure packages[wire](/modules/wire/)
* hand closure state to a package serializer without widening its public interface[wire](/modules/wire/)
Nothing matches. Try fewer words, or browse [all modules](/modules/).
Agents can do the same lookup offline: the installed package includes `node_modules/knotkit/capabilities.json`, and the [`knotkit-select` skill](/agents/#install-the-skill) reads it for them.
# Conventions
> Every module follows the same rules. Learn them once and the rest of the library reads the same way.
## Structures come from factories
[Section titled “Structures come from factories”](#structures-come-from-factories)
Every structure is created by a function and returned as a typed interface. There are no classes to instantiate or extend.
```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'
const heap = minBinaryHeap(numberOrder, [5, 8, 3])
heap.push(4)
heap.pop() // 3
```
The interface is the whole contract, so a structure is an ordinary value: pass it to a function, a test, or a benchmark. Every member is a `readonly` property, and destructuring a member keeps it working.
## Layouts are chosen by `kind`
[Section titled “Layouts are chosen by kind”](#layouts-are-chosen-by-kind)
When a module ships more than one implementation of the same interface, each one has its own factory and a `kind` string. `roaringBitset()` and `denseBitset()` both return a `Bitset`; their `kind` is `'roaring'` or `'dense'`.
Each module page has a **Choose a layout** table. Every row is a rule you can check against your workload, such as “you can name the largest id, and it fits in 64 MiB of bitmap”, followed by what that layout costs.
```ts
import { DISJOINT_SET_KINDS, __GROWABLE_DISJOINT_SET_LAYOUTS } from 'knotkit/disjoint-set'
DISJOINT_SET_KINDS // ['indexed', 'object', 'struct-of-arrays']
// Run the same test against every layout:
for (const [kind, create] of Object.entries(__GROWABLE_DISJOINT_SET_LAYOUTS)) {
// …
}
```
Branch on `kind`, not on `instanceof`. A `kind` survives serialization, iframes, and duplicate copies of the package in one bundle; `instanceof` does not.
## Errors carry codes
[Section titled “Errors carry codes”](#errors-carry-codes)
Every error is a subclass of `KnotkitError` with a `code` taken from a list the module exports, such as `HEAP_ERROR_CODES`. Each module’s errors fall into categories, such as invalid input (`HeapInvalidInputError`) or a failure to read saved data (`HeapParseError`).
```ts
import { isInvalidInputError } from 'knotkit/errors'
import { splitmix32, uniformInt } from 'knotkit/prng'
try {
uniformInt(splitmix32(42), 0)
} catch (error) {
if (isInvalidInputError(error) && error.moduleName === 'knotkit/prng') {
error.code // 'INVALID_BOUND'
}
}
```
Because the lists are exported as `as const` arrays, a `switch` over `error.code` can be exhaustive, and TypeScript reports a missing case when a release adds a code.
## Randomness, hashing, and ordering are arguments
[Section titled “Randomness, hashing, and ordering are arguments”](#randomness-hashing-and-ordering-are-arguments)
No module seeds itself, reads the clock, or picks a hash function for you. You pass them in:
```ts
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
const order = shuffled(splitmix32(42), [1, 2, 3, 4, 5]) // the same order on every machine
```
Record the seed and anyone can reproduce your result: a simulation, a sampled test, or a benchmark.
## Saving and loading is a separate import
[Section titled “Saving and loading is a separate import”](#saving-and-loading-is-a-separate-import)
Modules that can be saved expose `serialize*` and `deserialize*` from a `/wire` subpath, such as `knotkit/bitset/wire`. Code that never saves a structure never loads the parser.
Saved data is versioned and checked when it is read back. A truncated or tampered artifact fails with a parse error code, not a structure in a broken state.
## Costs are stated per member
[Section titled “Costs are stated per member”](#costs-are-stated-per-member)
Module pages list the time cost of each member where the module states one, with the conditions it depends on: `O(log c)` bitmap container, `O(1)` amortized. Measured speed-ups name their baseline and link the benchmark that produced them. See [Measured results](/evidence/).
# Agents
> Let your coding agent look up the right import, layout, and error codes for the version you use.
## Quick setup
[Section titled “Quick setup”](#quick-setup)
Paste this into your agent to install from source, add the selection skill, and show future sessions where to find the documentation.
Prompt · set up KnotkitCopy prompt
```
Set up Knotkit in this project.
1. Follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source to build and install the package. Use "bundler" or "nodenext" module resolution in TypeScript.
2. Run `npx skills add jkomyno/knotkit --skill knotkit-select` to install the skill that picks a module for a task.
3. Add this to AGENTS.md (or CLAUDE.md):
Knotkit: pick a module from node_modules/knotkit/capabilities.json, then read node_modules/knotkit//README.md. Import from 'knotkit/'; there is no root import. Create structures with the exported factory functions, branch on error.code, and pass seeds and orderings explicitly.
If something is unclear, read https://knotkit.jkomyno.dev/llms.txt.
```
## Read the docs as Markdown
[Section titled “Read the docs as Markdown”](#read-the-docs-as-markdown)
| URL | Contents |
| ------------------------ | --------------------------------------------------------------------------------- |
| `/llms.txt` | Start here for the full, abridged, and topic-specific bundles. |
| `/llms-small.txt` | Abridged documentation focused on usage, guides, and module pages. |
| `/llms-full.txt` | Full documentation, including the API reference. |
| `/.md` | Any single page: `/modules/heap/` is `/modules/heap.md`. |
| `/_llms-txt/.txt` | The module pages of one group, such as `collections.txt`. `/llms.txt` lists them. |
Every page also has a **Copy Markdown** control under its title, with a menu to open the Markdown twin, Claude, or ChatGPT.
## Install the skill
[Section titled “Install the skill”](#install-the-skill)
`knotkit-select` reads the capability index from your installed package. Ask your agent to merge several sorted feeds, for example, and the skill can look up the relevant exports and when to use them.
```bash
npx skills add jkomyno/knotkit --skill knotkit-select
```
The [`skills`](https://www.npmjs.com/package/skills) CLI needs Node.js 22.20 or later. Add `-g` to install for every project. Without the CLI, copy [`skills/knotkit-select`](https://github.com/jkomyno/knotkit/tree/main/skills/knotkit-select) into your agent’s skills directory.
## What ships in the package
[Section titled “What ships in the package”](#what-ships-in-the-package)
An agent working offline finds the same facts in `node_modules/knotkit`:
* `capabilities.json`: for every module, what it solves, what it is not for, its exports, the rule for choosing each layout, and its error codes.
* `/README.md`: usage, the full API with costs, and how the structure works.
* `/knotkit.capability.json`: one module’s record.
## A standing instruction
[Section titled “A standing instruction”](#a-standing-instruction)
For an `AGENTS.md` or `CLAUDE.md` without the skill:
```md
Knotkit: use node_modules/knotkit/capabilities.json or https://knotkit.jkomyno.dev/choosing.md to pick a module. Then
read its page at https://knotkit.jkomyno.dev/modules/.md. Import from 'knotkit/', create structures with
factories, branch on error.code, and pass seeds and orderings explicitly.
```
Each module page ends with a prompt specific to that module.
# Guides
> Run a TypeScript snippet in your browser, see what it returns, and adapt it to your project.
## Integrations
[Section titled “Integrations”](#integrations)
* [Build hybrid search for your docs](/guides/hybrid-docs-search/): Search Knotkit’s module docs by API name or by describing what you need.
* [Rate-limit an Effect endpoint](/guides/effect-rate-limit/): Give each API client a request budget and return HTTP 429 with a retry time.
## Queues and ordering
[Section titled “Queues and ordering”](#queues-and-ordering)
* [Keep the k largest values of a stream](/guides/top-k/): Hold a min heap of size `k` and replace its root whenever a larger value arrives.
* [Change the priority of queued work](/guides/reprioritize/): An indexed priority queue finds a queued item by its value and moves it in place.
* [Pick the k items that cover the most](/guides/budgeted-coverage/): Lazy greedy keeps every candidate in a max heap keyed by its last known gain and re-evaluates only the top.
* [Read the first n items of several sorted lists](/guides/merge-sorted/): Merge sorted inputs lazily, and stop as soon as you have enough.
* [Compute a rolling average over the last n values](/guides/rolling-average/): A bounded deque returns the value a push evicts, so the running sum subtracts exactly what left the window.
## Sets and caches
[Section titled “Sets and caches”](#sets-and-caches)
* [Deduplicate records by numeric id](/guides/dedupe-ids/): A Roaring bitset records which ids you have seen in about two bytes per id, or one bit per possible id once ids are dense.
* [Cap a cache by entry count](/guides/bounded-cache/): A SIEVE cache keeps at most `capacity` entries and returns what it evicted from every `set`.
* [Limit each client to a request rate](/guides/per-client-rate-limit/): A keyed table builds one rate-limit meter per client, spends and refuses weight on that client alone, and forgets a client only once its meter would decide like a fresh one.
* [Find which items are connected](/guides/connected-groups/): A disjoint set merges groups as links arrive and answers whether two items are in the same group.
## Randomness and statistics
[Section titled “Randomness and statistics”](#randomness-and-statistics)
* [Shuffle reproducibly from a seed](/guides/seeded-shuffle/): Pass a seeded random source to `shuffled`, and the same seed gives the same order on every machine.
* [Sample a stream of unknown length](/guides/stream-sample/): A reservoir sampler keeps a uniform sample of fixed size, however many items pass through.
* [Test whether two samples differ](/guides/compare-samples/): The Mann–Whitney U test compares two independent samples without assuming they are normal.
## Saving and loading
[Section titled “Saving and loading”](#saving-and-loading)
* [Save a structure and load it back](/guides/save-and-load/): Serialization lives in a `/wire` subpath. It writes versioned bytes and restores the same layout.
## Larger examples
[Section titled “Larger examples”](#larger-examples)
See how the same modules work together on larger workloads, from [road routing](/problems/road-network/) to [near-duplicate detection](/problems/near-duplicate-detection/). [Browse all examples](/problems/).
# Cap a cache by entry count
> A SIEVE cache keeps at most capacity entries and returns what it evicted from every set.
Few itemsThousands of items
●
ResetEditRun
```ts
import { sieveCache } from 'knotkit/cache'
const cache = sieveCache({ capacity: 2 })
cache.set('a', 1) // []
cache.set('b', 2) // []
cache.get('a') // 1
cache.set('c', 3) // [{ key: 'b', value: 2 }], what was evicted to make room
cache.peek('b') // undefined
cache.size // 2
```
```ts
import { sieveCache } from 'knotkit/cache'
const cache = sieveCache({ capacity: 1_000 })
let evicted = 0
// 100 hot keys, read again between 20,000 inserts of keys seen once.
const hot = Array.from({ length: 100 }, (_, index) => index)
for (const key of hot) {
cache.set(key, `value-${key}`)
}
for (let index = 100; index < 20_100; index += 1) {
cache.get(index % 100)
evicted += cache.set(index, `value-${index}`).length
}
cache.size // 1000
evicted // 19100, every insert after the first 1,000 evicted one entry
hot.every((key) => cache.peek(key) !== undefined) // true, a read marks a key and the eviction hand skips it
cache.peek(1_000) // undefined, a key read once is gone
```
```
```
The same options also bound total weight with `weigh`, and expire entries with `timeToLive` and a clock you pass in. The module page compares SIEVE, LRU, and S3-FIFO on a scan-heavy trace.
**Modules:** [`knotkit/cache`](/modules/cache/) · [API reference](/reference/knotkit/cache/)
# Pick the k items that cover the most
> Lazy greedy keeps every candidate in a max heap keyed by its last known gain and re-evaluates only the top.
Few itemsThousands of items
●
ResetEditRun
```ts
import { mapInputOrder, maxBinaryHeap, numberOrder } from 'knotkit/heap'
// Each candidate reaches some users; pick the two that reach the most users together.
const audiences = [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const reached = new Set()
const gainOf = (index: number): number => (audiences[index] ?? []).filter((user) => !reached.has(user)).length
interface Candidate {
readonly index: number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly gain: number
}
const byGain = mapInputOrder(numberOrder, (candidate: Candidate) => candidate.gain)
const frontier = maxBinaryHeap(
byGain,
audiences.map((_, index) => ({ index, gain: gainOf(index) })),
)
const picks: number[] = []
while (picks.length < 2) {
const top = frontier.peek()
const fresh = gainOf(top.index)
if (fresh < top.gain) {
frontier.replaceRoot({ ...top, gain: fresh }) // stale bound: lower it and look again
continue
}
frontier.pop()
picks.push(top.index)
for (const user of audiences[top.index] ?? []) {
reached.add(user)
}
}
picks // [0, 2]
reached.size // 5
```
```ts
import { mapInputOrder, maxBinaryHeap, numberOrder } from 'knotkit/heap'
import { splitmix32, uniformInt } from 'knotkit/prng'
const random = splitmix32(2026)
const k = 20
// 5,000 candidates over 2,000 users. Each candidate reaches between 1 and 60 seeded users, so audiences overlap.
const audiences = Array.from({ length: 5_000 }, () => {
const size = 1 + uniformInt(random, 60)
return new Set(Array.from({ length: size }, () => uniformInt(random, 2_000)))
})
const reached = new Set()
let evaluations = 0
const gainOf = (index: number): number => {
evaluations += 1
let gain = 0
for (const user of audiences[index] ?? []) {
if (!reached.has(user)) {
gain += 1
}
}
return gain
}
interface Candidate {
readonly index: number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly gain: number
}
const byGain = mapInputOrder(numberOrder, (candidate: Candidate) => candidate.gain)
const frontier = maxBinaryHeap(
byGain,
audiences.map((_, index) => ({ index, gain: gainOf(index) })),
)
const picks: number[] = []
while (picks.length < k) {
const top = frontier.peek()
const fresh = gainOf(top.index)
if (fresh < top.gain) {
frontier.replaceRoot({ ...top, gain: fresh }) // stale bound: lower it and look again
continue
}
frontier.pop()
picks.push(top.index)
for (const user of audiences[top.index] ?? []) {
reached.add(user)
}
}
picks.length // 20
reached.size // 999
evaluations - audiences.length // 2853, after seeding the heap
k * audiences.length // 100000, re-scoring every candidate for every pick
```
```
```
Gains only shrink as the selection grows, so a stale gain is an upper bound: when the refreshed top still beats every other bound, it is the greedy choice without evaluating the rest. [The algorithm page](/problems/budget-allocation/) explains the guarantee and the measured savings.
**Modules:** [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/heap/)
# Test whether two samples differ
> The Mann–Whitney U test compares two independent samples without assuming they are normal.
Few itemsThousands of items
●
ResetEditRun
```ts
import { mannWhitneyUTest } from 'knotkit/hypothesis-test'
// Page load times in milliseconds, before and after a change.
const before = [412, 398, 455, 430, 441, 420, 409, 437]
const after = [380, 372, 401, 366, 390, 384, 377, 395]
const result = mannWhitneyUTest(before, after)
result.pValue < 0.05 // true
result.pValue.toFixed(4) // '0.0003'
```
```ts
import { logNormalDistribution } from 'knotkit/distribution'
import { mannWhitneyUTest } from 'knotkit/hypothesis-test'
import { splitmix32 } from 'knotkit/prng'
// Page load times in milliseconds, before and after a change, drawn from two seeded right-skewed models.
const before = logNormalDistribution({ logMean: Math.log(400), logStandardDeviation: 0.5 })
const after = logNormalDistribution({ logMean: Math.log(380), logStandardDeviation: 0.5 })
const beforeRandom = splitmix32(1)
const afterRandom = splitmix32(2)
const beforeSamples = Array.from({ length: 5_000 }, () => before.draw(beforeRandom))
const afterSamples = Array.from({ length: 5_000 }, () => after.draw(afterRandom))
const result = mannWhitneyUTest(beforeSamples, afterSamples)
const median = (samples: readonly number[]): number => {
const sorted = samples.toSorted((left, right) => left - right)
return (sorted[sorted.length / 2 - 1]! + sorted[sorted.length / 2]!) / 2
}
beforeSamples.length // 5000
result.pValue < 0.001 // true, the samples differ
Math.round(median(beforeSamples)) // 397
Math.round(median(afterSamples)) // 379, the medians say by how much
```
```
```
A small p-value says the samples differ, not by how much, so report a difference such as the medians beside it. Its p-values agree with SciPy to `1e-9`. For a difference in means with roughly normal data, use `welchTTest`. For paired measurements, use `pairedTTest`.
**Modules:** [`knotkit/hypothesis-test`](/modules/hypothesis-test/) · [API reference](/reference/knotkit/hypothesis-test/)
# Find which items are connected
> A disjoint set merges groups as links arrive and answers whether two items are in the same group.
Few itemsThousands of items
●
ResetEditRun
```ts
import { objectDisjointSet } from 'knotkit/disjoint-set'
const accounts = objectDisjointSet(['ada', 'grace', 'alan', 'edsger'])
// Accounts that share an email address belong to the same person.
accounts.unite('ada', 'grace') // true
accounts.unite('grace', 'alan') // true
accounts.unite('ada', 'alan') // false, already connected
accounts.areConnected('ada', 'alan') // true
accounts.areConnected('ada', 'edsger') // false
accounts.setCount // 2
```
```ts
import { objectDisjointSet } from 'knotkit/disjoint-set'
import { splitmix32, uniformInt } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
const random = splitmix32(2026)
// 10,000 accounts. A chain of 9,999 links joins them all, and 1,000 seeded extra links repeat what the chain already joins.
const accounts = objectDisjointSet(Array.from({ length: 10_000 }, (_, index) => `account-${index}`))
const chain = Array.from({ length: 9_999 }, (_, index) => [index, index + 1] as const)
const extra = Array.from({ length: 1_000 }, () => {
const left = uniformInt(random, 10_000)
return [left, (left + 1 + uniformInt(random, 9_999)) % 10_000] as const
})
const links = shuffled(random, [...chain, ...extra])
let merged = 0
let redundant = 0
for (const [left, right] of links) {
if (accounts.unite(`account-${left}`, `account-${right}`)) {
merged += 1
} else {
redundant += 1
}
}
accounts.setCount // 1
merged // 9999, one per account after the first
redundant // 1000, links between accounts that were already connected
accounts.areConnected('account-0', 'account-9999') // true
```
```
```
`unite` returns `false` when the two items were already connected, which is how Kruskal and cycle detection count useful edges. Use `indexedDisjointSet` when the items are dense integer ids.
**Modules:** [`knotkit/disjoint-set`](/modules/disjoint-set/) · [API reference](/reference/knotkit/disjoint-set/)
# Deduplicate records by numeric id
> A Roaring bitset records which ids you have seen in about two bytes per id, or one bit per possible id once ids are dense.
Few itemsThousands of items
●
ResetEditRun
```ts
import { roaringBitset } from 'knotkit/bitset'
const rows = [
{ id: 7, name: 'ada' },
{ id: 4, name: 'grace' },
{ id: 7, name: 'ada' },
]
const seen = roaringBitset()
const unique = rows.filter((row) => {
if (seen.has(row.id)) {
return false
}
seen.add(row.id)
return true
})
unique.map((row) => row.name) // ['ada', 'grace']
seen.size // 2
```
```ts
import { roaringBitset } from 'knotkit/bitset'
import { serializeBitset } from 'knotkit/bitset/wire'
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
// 20,000 rows over 10,000 distinct ids, arriving in shuffled order.
const rows = Array.from({ length: 20_000 }, (_, index) => ({ id: index % 10_000, name: `row-${index}` }))
const arrivals = shuffled(splitmix32(2026), rows)
const seen = roaringBitset()
const unique = arrivals.filter((row) => {
if (seen.has(row.id)) {
return false
}
seen.add(row.id)
return true
})
unique.length // 10000
seen.size // 10000
serializeBitset(seen).byteLength // 8272, one bit per possible id from 0 to 65,535 rather than one object per row
```
```
```
Ids must be integers from 0 to 2³² − 1. For other keys, a `Set` is the right tool.
**Modules:** [`knotkit/bitset`](/modules/bitset/) · [API reference](/reference/knotkit/bitset/)
# Rate-limit an Effect endpoint
> Give each API client a request budget and return HTTP 429 with a retry time.
## Try a burst
[Section titled “Try a burst”](#try-a-burst)
1. Click **Send 5 requests** at time zero. The first three return `200`. The next two return `429` with `Retry-After: 5`.
2. Enter another client ID and click **Send request**. That client still has its own budget.
3. Return to the first client, click **Advance 5 seconds**, and send again. The demo uses a manual clock so you can try a new window immediately.
## Run the TypeScript
[Section titled “Run the TypeScript”](#run-the-typescript)
Use [Knotkit from source](/getting-started/#install-from-source) and install `effect@4.1.7`. Call `rateLimitedHandler(handle)` once at startup. Pass the returned handler an authenticated client ID for each request.
The admission check takes one unit when the Effect runs. A rejection enters the [typed error channel](https://effect.website/docs/v4/error-management/expected-errors). At the HTTP boundary, `Effect.matchEffect` calls your handler for accepted requests and turns quota denials into [HTTP 429](https://www.rfc-editor.org/rfc/rfc6585.html#section-4). Round Knotkit’s millisecond delay up to whole seconds for [Retry-After](https://www.rfc-editor.org/rfc/rfc9110.html#name-retry-after). Errors from your handler still reach its caller.
The table is bounded and lives in one process. When all slots are busy, a new client receives `503`. A quota shared across service replicas needs shared state. See [the rate-limit module](/modules/rate-limit/) for other meter choices.
```ts
import { Effect } from 'effect'
import { fixedWindowRateLimiter, keyedRateLimitTable, type KeyedRateLimitTable } from 'knotkit/rate-limit'
export const requestLimit = 3
export const windowMilliseconds = 5_000
export function admitRequest(limits: KeyedRateLimitTable, clientId: string) {
return Effect.suspend(() => {
const decision = limits.take(clientId, 1)
return decision.outcome === 'allowed' ? Effect.void : Effect.fail(decision)
})
}
export function rateLimitedHandler(
handle: (clientId: string) => Effect.Effect,
clock: () => number = () => Math.floor(performance.now()),
) {
const limits = keyedRateLimitTable({
clock,
maxKeyCount: 1024,
whenFull: 'refuse',
meter: (meterClock) =>
fixedWindowRateLimiter({ capacity: requestLimit, windowDuration: windowMilliseconds, clock: meterClock }),
})
return (clientId: string): Effect.Effect =>
Effect.matchEffect(admitRequest(limits, clientId), {
onSuccess: () => handle(clientId),
onFailure: (decision) => {
if (decision.outcome !== 'denied') {
return Effect.succeed(Response.json({ error: decision.outcome }, { status: 503 }))
}
const retryAfter = Math.ceil(decision.retryAfter / 1000)
return Effect.succeed(
Response.json(
{ error: 'too_many_requests' },
{ status: 429, headers: { 'Retry-After': String(retryAfter) } },
),
)
},
})
}
```
**Modules:** [`knotkit/rate-limit`](/modules/rate-limit/) · [API reference](/reference/knotkit/rate-limit/)
# Build hybrid search for your docs
> Search Knotkit’s module docs by API name or by describing what you need.
`compressedSparseRowGraph`
Looking for [knotkit/graph](/modules/graph/)
## Keyword
BM25
1. [graph](/modules/graph/)
## Semantic
Embedding similarity
1. [graph](/modules/graph/)
2. [trie](/modules/trie/)
3. [prng](/modules/prng/)
4. [scalar-sketch](/modules/scalar-sketch/)
5. [sampling](/modules/sampling/)
## Hybrid
Rank fusion
1. [graph](/modules/graph/)
2. [trie](/modules/trie/)
3. [prng](/modules/prng/)
4. [scalar-sketch](/modules/scalar-sketch/)
5. [sampling](/modules/sampling/)
Showing up to 5 results from 32 module summaries.
## Try your own query
[Section titled “Try your own query”](#try-your-own-query)
Type a task you’re working on or a function name, then press **Search**. Compare the results under **Keyword**, **Semantic**, and **Hybrid**. Keyword results appear while a worker loads the embedding model for the first custom query. The worker encodes your text in your browser and reuses the model for later searches.
Use **API name** to find `compressedSparseRowGraph`. Try **Customer quotas** to find the rate-limit module by meaning. **Sample a stream** shows a query where both methods put the same module first.
## Run the TypeScript
[Section titled “Run the TypeScript”](#run-the-typescript)
Knotkit builds the keyword index once. NumPyTS multiplies the document matrix by the query vector to score every document. With unit-length embeddings, the dot product is cosine similarity. [Reciprocal rank fusion](https://cormack.uwaterloo.ca/cormack/cormacksigir09-rrf.pdf) combines the first ten hits from each method. A document gets more credit for appearing higher in either list.
Use [Knotkit from source](/getting-started/#install-from-source) and install `numpy-ts@1.8.0`. Pass documents and query vectors produced by the same embedding model.
The demo bundles [BGE-small embeddings](https://huggingface.co/BAAI/bge-small-en-v1.5) for the module summaries and example queries. The first custom search downloads the 34 MB model and the WebAssembly runtime. The fixture generator at `apps/docs/scripts/embed-hybrid-search.py` records the model revision and reads the module summaries and API names from the capability catalog.
```ts
import { termIndex } from 'knotkit/term-index'
import { array, matmul } from 'numpy-ts/core'
interface SearchDocument {
readonly text: string
readonly embedding: ArrayLike
}
const shortlistSize = 10
const rankOffset = 60
const stopWords = new Set(
'a an and are as at be by can do each for from give how i in into is it of on or please that the to with you'.split(
' ',
),
)
const terms = (text: string): string[] =>
(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).filter((term) => !stopWords.has(term))
export function hybridDocSearch(documents: readonly SearchDocument[]) {
const index = termIndex(documents, ({ text }) => terms(text))
const matrix = array(
documents.map(({ embedding }) => Array.from(embedding)),
'float64',
)
return (query: string, embedding?: ArrayLike) => {
const keyword = index.search(terms(query), { limit: shortlistSize }).map(({ id }) => id)
if (embedding === undefined) {
return { keyword, semantic: [], hybrid: [] }
}
const queryVector = array(Float64Array.from(embedding), 'float64')
const similarities = new Float64Array(matmul(matrix, queryVector).tobytes())
const semantic = Array.from(similarities.keys())
.toSorted((a, b) => similarities[b] - similarities[a] || a - b)
.slice(0, shortlistSize)
const scores = new Map()
for (const ranking of [keyword, semantic]) {
for (const [rank, id] of ranking.entries()) {
scores.set(id, (scores.get(id) ?? 0) + 1 / (rankOffset + rank + 1))
}
}
const hybrid = Array.from(scores.entries())
.toSorted(([a, left], [b, right]) => right - left || a - b)
.map(([id]) => id)
return { keyword, semantic, hybrid }
}
}
```
**Modules:** [`knotkit/term-index`](/modules/term-index/) · [API reference](/reference/knotkit/term-index/)
# Read the first n items of several sorted lists
> Merge sorted inputs lazily, and stop as soon as you have enough.
Few itemsThousands of items
●
ResetEditRun
```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'
const shards = [
[1, 4, 9, 12],
[2, 3, 10],
[5, 6, 7, 8],
]
const firstFive: number[] = []
for (const id of mergeSorted(numberOrder, shards)) {
firstFive.push(id)
if (firstFive.length === 5) {
break // closes every shard; the rest is never read
}
}
firstFive // [1, 2, 3, 4, 5]
```
```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'
let reads = 0
// 16 shards holding the ids 0 to 65,535 between them, each shard already sorted.
function* shard(index: number): Generator {
for (let offset = 0; offset < 4_096; offset += 1) {
reads += 1
yield index + offset * 16
}
}
const shards = Array.from({ length: 16 }, (_, index) => shard(index))
const page: number[] = []
for (const id of mergeSorted(numberOrder, shards)) {
page.push(id)
if (page.length === 32) {
break // closes every shard
}
}
page.length // 32
page.at(-1) // 31, the last id a 32-row page needs
reads // 47, out of the 65,536 ids the shards hold
```
```
```
The merge reads one item per input to start, then only from the input it last took from. Breaking out of the loop closes every input, so a page of results costs the page, not the whole input.
**Modules:** [`knotkit/sorted-merge`](/modules/sorted-merge/) · [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/sorted-merge/)
# Limit each client to a request rate
> A keyed table builds one rate-limit meter per client, spends and refuses weight on that client alone, and forgets a client only once its meter would decide like a fresh one.
Few itemsThousands of items
●
ResetEditRun
```ts
import { fixedWindowRateLimiter, keyedRateLimitTable } from 'knotkit/rate-limit'
let now = 0
const limits = keyedRateLimitTable({
maxKeyCount: 1,
whenFull: 'refuse',
clock: () => now,
meter: (clock) => fixedWindowRateLimiter({ capacity: 2, windowDuration: 1_000, clock }),
})
limits.take('client-a', 1) // { outcome: 'allowed', untracked: false }
limits.take('client-a', 1) // { outcome: 'allowed', untracked: false }
limits.take('client-a', 1) // { outcome: 'denied', retryAfter: 1_000 }
limits.take('client-b', 1) // { outcome: 'refused' }, the only slot holds a client in debt
now = 1_000
limits.take('client-b', 1) // { outcome: 'allowed', untracked: false }, client-a's window ended, so the table forgot it
limits.take('client-b', 3) // { outcome: 'never-fits' }, no wait makes weight 3 fit a capacity of 2
limits.size // 1
```
```ts
import { fixedWindowRateLimiter, keyedRateLimitTable } from 'knotkit/rate-limit'
let now = 0
const limits = keyedRateLimitTable({
maxKeyCount: 1_000,
whenFull: 'refuse',
clock: () => now,
meter: (clock) => fixedWindowRateLimiter({ capacity: 2, windowDuration: 1_000, clock }),
})
function requests(firstClient: number, endClient: number, each: number): Record {
const outcomes: Record = {}
for (let client = firstClient; client < endClient; client += 1) {
for (let request = 0; request < each; request += 1) {
const { outcome } = limits.take(`client-${client}`, 1)
outcomes[outcome] = (outcomes[outcome] ?? 0) + 1
}
}
return outcomes
}
// 4,000 clients, three requests each, inside one window, into a table that holds 1,000.
requests(0, 4_000, 3) // { allowed: 2000, denied: 1000, refused: 9000 }
limits.size // 1000
// One window later the first 1,000 meters are fresh, so the table forgets them to admit new clients.
now = 1_000
requests(1_000, 4_000, 1) // { allowed: 1000, refused: 2000 }
limits.size // 1000
```
```
```
The table holds at most `maxKeyCount` clients, and `whenFull` decides what a client it cannot hold is told. On the pinned per-client trace, the `fixed-window` meter this snippet uses keeps 64 clients in 52.6 KB where a `Map` of counters keeps 4,146 in 684.1 KB, at about 7 times the cost per decision: [the measurements](/problems/per-client-rate-limit/).
**Modules:** [`knotkit/rate-limit`](/modules/rate-limit/) · [API reference](/reference/knotkit/rate-limit/)
# Change the priority of queued work
> An indexed priority queue finds a queued item by its value and moves it in place.
Few itemsThousands of items
●
ResetEditRun
```ts
import { minPriorityQueue, numberOrder } from 'knotkit/heap'
// [priority, task]: the lowest priority runs first.
const queue = minPriorityQueue(numberOrder, [
[5, 'render'],
[1, 'parse'],
[3, 'layout'],
])
queue.updateKey(0, 'layout') // a user is now waiting on layout
queue.pop() // 'layout'
queue.pop() // 'parse'
queue.size // 1
```
```ts
import { minPriorityQueue, numberOrder } from 'knotkit/heap'
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
// 10,000 queued tasks, handed to the queue in shuffled order.
const tasks: [number, string][] = Array.from({ length: 10_000 }, (_, index) => [(index % 100) + 1, `task-${index}`])
const queue = minPriorityQueue(numberOrder, shuffled(splitmix32(2026), tasks))
// Key 0 is lower than every queued key, so this task is next out.
queue.updateKey(0, 'task-7777') // a user is now waiting on task 7777
queue.size // 10000
queue.pop() // 'task-7777'
queue.size // 9999
```
```
```
Use an indexed queue when jobs can change priority while they wait. The first key lookup or update builds the index in `O(n)`. After that, a binary queue finds an entry by value and changes its priority in `O(log n)`.
**Modules:** [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/heap/)
# Compute a rolling average over the last n values
> A bounded deque returns the value a push evicts, so the running sum subtracts exactly what left the window.
Few itemsThousands of items
●
ResetEditRun
```ts
import { float64ArrayDeque } from 'knotkit/deque'
const window = float64ArrayDeque({ capacity: 3 })
let sum = 0
function observe(value: number): number {
sum += value
const evicted = window.pushBack(value) // undefined until the window is full
if (evicted !== undefined) {
sum -= evicted
}
return sum / window.size
}
observe(10) // 10
observe(20) // 15
observe(30) // 20
observe(40) // 30, after 10 left the window
```
```ts
import { float64ArrayDeque } from 'knotkit/deque'
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
const window = float64ArrayDeque({ capacity: 3 })
let sum = 0
function observe(value: number): number {
sum += value
const evicted = window.pushBack(value) // undefined until the window is full
if (evicted !== undefined) {
sum -= evicted
}
return sum / window.size
}
// 50,000 observations: the values 0 to 99, repeated 500 times, in shuffled order.
const values = shuffled(
splitmix32(2026),
Array.from({ length: 50_000 }, (_, index) => index % 100),
)
let average = 0
for (const value of values) {
average = observe(value)
}
window.size // 3
values.slice(-3) // [6, 91, 42]
average === (6 + 91 + 42) / 3 // true, the mean of the last three values only
```
```
```
Each observation is `O(1)`. The `Float64Array` layout stores eight bytes per slot and accepts only numbers. Use `arrayDeque` for other values.
**Modules:** [`knotkit/deque`](/modules/deque/) · [API reference](/reference/knotkit/deque/)
# Save a structure and load it back
> Serialization lives in a /wire subpath. It writes versioned bytes and restores the same layout.
Few itemsThousands of items
●
ResetEditRun
```ts
import { roaringBitset } from 'knotkit/bitset'
import { deserializeBitset, serializeBitset } from 'knotkit/bitset/wire'
const ids = roaringBitset({ items: [7, 42, 2 ** 31] })
const bytes = serializeBitset(ids, { integrity: true }) // a Uint8Array to store anywhere
const restored = deserializeBitset(bytes)
restored.kind // 'roaring'
restored.has(42) // true
restored.size // 3
```
```ts
import { roaringBitset } from 'knotkit/bitset'
import { deserializeBitset, serializeBitset } from 'knotkit/bitset/wire'
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
// 50,000 ids from 0 to 49,999, added in shuffled order.
const ids = shuffled(
splitmix32(2026),
Array.from({ length: 50_000 }, (_, index) => index),
)
const set = roaringBitset({ items: ids })
const bytes = serializeBitset(set, { integrity: true })
const restored = deserializeBitset(bytes)
restored.kind // 'roaring'
restored.size // 50000
restored.has(49_999) // true
bytes.byteLength // 8288, the ids fill one dense chunk: a bitmap of 8 KiB for each 65,536 possible ids
```
```
```
With `integrity` set, a corrupted artifact fails with a parse error code instead of loading. Code that never saves a structure never imports the parser.
**Modules:** [`knotkit/bitset`](/modules/bitset/) · [API reference](/reference/knotkit/bitset/)
# Shuffle reproducibly from a seed
> Pass a seeded random source to shuffled, and the same seed gives the same order on every machine.
Few itemsThousands of items
●
ResetEditRun
```ts
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
const players = ['ada', 'grace', 'alan', 'edsger', 'barbara']
const first = shuffled(splitmix32(2026), players)
const again = shuffled(splitmix32(2026), players)
first // ['ada', 'grace', 'edsger', 'barbara', 'alan']
first.join() === again.join() // true
players // ['ada', 'grace', 'alan', 'edsger', 'barbara'], the input is untouched
```
```ts
import { splitmix32 } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'
// 10,000 players, each with an id.
const players = Array.from({ length: 10_000 }, (_, index) => `player-${index}`)
const first = shuffled(splitmix32(2026), players)
const again = shuffled(splitmix32(2026), players)
first.length // 10000
first.join() === again.join() // true, the seed replays the same order
players[0] // 'player-0', the input is untouched
```
```
```
Nothing in Knotkit seeds itself. Record the seed with the result, and anyone can replay it.
**Modules:** [`knotkit/sampling`](/modules/sampling/) · [`knotkit/prng`](/modules/prng/) · [API reference](/reference/knotkit/sampling/)
# Sample a stream of unknown length
> A reservoir sampler keeps a uniform sample of fixed size, however many items pass through.
Few itemsThousands of items
●
ResetEditRun
```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'
const sampler = reservoirSampler(splitmix32(7), 3)
for (const request of ['GET /', 'GET /a', 'POST /b', 'GET /c', 'GET /d', 'PUT /e']) {
sampler.add(request)
}
sampler.snapshot() // ['PUT /e', 'GET /c', 'POST /b']
```
```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'
const sampler = reservoirSampler(splitmix32(7), 5)
// 50,000 requests, and no count kept anywhere else.
for (let index = 0; index < 50_000; index += 1) {
sampler.add(index)
}
const sample = sampler.snapshot()
sample // [9113, 47886, 47206, 27133, 11142], five of the 50,000, however long the stream ran
new Set(sample).size // 5, no item appears twice
```
```
```
Every item seen so far has the same chance of being in the sample. Memory is the sample size, not the stream length.
**Modules:** [`knotkit/sampling`](/modules/sampling/) · [`knotkit/prng`](/modules/prng/) · [API reference](/reference/knotkit/sampling/)
# Keep the k largest values of a stream
> Hold a min heap of size k and replace its root whenever a larger value arrives.
Few itemsThousands of items
●
ResetEditRun
```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'
const k = 3
const largest = minBinaryHeap(numberOrder)
for (const latency of [120, 45, 300, 87, 210, 95, 410]) {
if (largest.size < k) {
largest.push(latency)
} else if (latency > largest.peek()) {
largest.replaceRoot(latency)
}
}
const top: number[] = []
while (largest.size > 0) {
top.push(largest.pop())
}
top // [210, 300, 410]
```
```ts
import { minBinaryHeap, numberOrder } from 'knotkit/heap'
import { splitmix32, uniformInt } from 'knotkit/prng'
const k = 3
const random = splitmix32(2026)
// 20,000 request latencies in arrival order, plus one outlier inserted at a seeded position.
const latencies = Array.from({ length: 20_000 }, () => uniformInt(random, 1_000) + 1)
latencies.splice(uniformInt(random, latencies.length), 0, 1_500)
latencies.indexOf(1_500) // 1710
const largest = minBinaryHeap(numberOrder)
for (const latency of latencies) {
if (largest.size < k) {
largest.push(latency)
} else if (latency > largest.peek()) {
largest.replaceRoot(latency)
}
}
const top: number[] = []
while (largest.size > 0) {
top.push(largest.pop())
}
// The heap held three values through 20,001 arrivals.
top // [1000, 1000, 1500]
top[2] // 1500, the outlier survived every replacement
largest.size // 0
```
```
```
Each value costs one comparison against the root and, when it is admitted, one sift of `O(log k)`. Memory stays at `k` values however long the stream runs.
**Modules:** [`knotkit/heap`](/modules/heap/) · [API reference](/reference/knotkit/heap/)
# Modules
> Every module in the package, grouped by what you are doing.
Import each one by its subpath, `knotkit/`.
Filter 32 modules by name, export, or task…
## Collections
Queues, heaps, sets, maps, interval indexes, sorted blocks, caches, and rate limits.
* [bitsetProvides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks](/modules/bitset/)
* [cacheBounds an in-memory key-value store by entry count or total weight, with least-recently-used, SIEVE, S3-FIFO, or caller-supplied eviction and optional expiry](/modules/cache/)
* [dequeQueues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window](/modules/deque/)
* [disjoint-setTracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts](/modules/disjoint-set/)
* [frequency-tableMaintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain](/modules/frequency-table/)
* [heapProvides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators](/modules/heap/)
* [interval-indexIndexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range](/modules/interval-index/)
* [ordered-mapStores keys in comparator order with insertion, deletion, rank, selection, ceiling, floor, and range scans in either direction, as a B-tree or an indexed skip list](/modules/ordered-map/)
* [rate-limitLimits each client's request weight by a fixed window, a sliding window, or a token bucket, returning the least whole millisecond a denial must wait](/modules/rate-limit/)
* [snapshot-setKeeps every snapshot readable for the lifetime of the set, at O(1) mutation and snapshot cost](/modules/snapshot-set/)
* [sorted-blockPacks byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans](/modules/sorted-block/)
* [sorted-mergeLazily merges sorted iterables in comparator order, preserving duplicates and source order on ties](/modules/sorted-merge/)
## Search and text
Prefix lookup, posting lists, and ranked retrieval.
* [inverted-indexIndexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists](/modules/inverted-index/)
* [prefix-indexEnumerates a bounded number of distinct strings that start with a prefix in UTF-16 order](/modules/prefix-index/)
* [term-indexIndexes tokenized documents with exact term counts and ranks matching document IDs by BM25](/modules/term-index/)
* [trieResolves delimiter-separated token keys by longest prefix in a single walk](/modules/trie/)
## Graphs and optimization
Traversal, shortest paths, rewriting, and search.
* [combinatoricsCounts permutations, combinations, cycles, and set partitions exactly or in log space](/modules/combinatorics/)
* [e-graphPropagates equalities through expressions and extracts a minimum-cost equivalent expression](/modules/e-graph/)
* [evolutionRuns deterministic population evolution with index-based parent selection and immutable permutation operators](/modules/evolution/)
* [graphProvides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix](/modules/graph/)
## Randomness and statistics
Seeded sources, sampling, distributions, tests, sketches, and static filters.
* [distanceCompares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees](/modules/distance/)
* [distributionComputes probabilities, quantiles, moments, and seeded draws for named and caller-defined distributions](/modules/distribution/)
* [hypothesis-testComputes t-test, ANOVA, rank-test, goodness-of-fit, and exact-test p-values for counts, samples, and contingency tables](/modules/hypothesis-test/)
* [prngGenerates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests](/modules/prng/)
* [samplingDraws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness](/modules/sampling/)
* [scalar-sketchProvides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains](/modules/scalar-sketch/)
* [static-filterBuilds immutable Binary Fuse membership filters over a known set of byte keys, with no false negatives and fewer bytes than a Bloom filter at the same false-positive rate](/modules/static-filter/)
## Serialization and utilities
Hashing, order-preserving keys, error classes, and binary envelopes.
* [casAddresses wire-envelope artifacts by content hash and stores them through an injected backend](/modules/cas/)
* [errorsProvides the base error classes every Knotkit package throws from, discriminated by package, category, and cause](/modules/errors/)
* [hashComputes deterministic non-cryptographic XXH64 hashes, identical across browsers, Node.js, and Bun](/modules/hash/)
* [key-encodingEncodes integers, doubles, byte strings, strings, and tuples of them as byte keys whose unsigned byte order matches the values' order](/modules/key-encoding/)
* [wireEncodes bounded binary envelopes and element codecs for Knotkit structures](/modules/wire/)
No module matches. Try describing the task on [Choose a module](/choosing/).
# knotkit/bitset
> Provides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks
## Use
[Section titled “Use”](#use)
```ts
import { roaringBitset } from 'knotkit/bitset'
const rows = [{ id: 7 }, { id: 4 }, { id: 7 }]
const seen = roaringBitset()
const unique = []
for (const row of rows) {
if (seen.has(row.id)) {
continue
}
seen.add(row.id)
unique.push(row)
}
seen.size // 2, exact and O(1)
```
bitset.ts●
ResetEditRun
```
```
```ts
import { denseBitset } from 'knotkit/bitset'
const todayIds = [40, 41, 42, 43, 44]
const yesterdayIds = [42, 43, 44, 45]
const today = denseBitset({ items: todayIds })
const yesterday = denseBitset({ items: yesterdayIds })
today.addAll(yesterday) // union: ids added
today.retainAll(yesterday) // intersection: ids deleted
today.deleteAll(yesterday) // difference: ids deleted
today.intersectionSize(yesterday) // |A ∩ B|, allocating nothing
```
```ts
import { roaringBitset } from 'knotkit/bitset'
const ids = roaringBitset({ items: [2, 5, 9] })
ids.at(0) // 2, the smallest
ids.at(-1) // 9, the largest
ids.rank(3) // 1, ids at or below 3
ids.ceiling(3) // 5, the next id at or above 3
ids.ceiling(10) // undefined
ids.floor(8) // 5, the previous id at or below 8
ids.floor(1) // undefined
ids.countRange(0, 6) // 2, ids in [0, 6)
```
```ts
import { denseBitset } from 'knotkit/bitset'
const slots = denseBitset()
slots.addRange(0, 1_000) // 1,000 ids added
slots.deleteRange(500, 600) // 100 ids deleted
```
```ts
import { roaringBitset } from 'knotkit/bitset'
const cached = roaringBitset({ items: [1, 2, 3] })
const requested = new Set([2, 3, 9])
// A native Set, built from the bitset, without materializing its ids first.
new Set(requested.union(cached)) // Set { 2, 3, 9, 1 }
requested.isSubsetOf(cached) // false
new Set(cached) // Set { 1, 2, 3 }
// And the other way round: a bitset compares against any set-like.
cached.isSubsetOf(requested) // false
cached.intersectionSize(requested) // 2
```
```ts
import { __BITSET_LAYOUTS, roaringBitset } from 'knotkit/bitset'
const a = roaringBitset({ items: [1, 2] })
const b = roaringBitset({ items: [2, 3] })
const union = __BITSET_LAYOUTS[a.kind]({ items: a })
union.addAll(b) // a ∪ b; a and b are untouched
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* filter membership over millions of non-negative integer ids without paying a byte per possible id
* combine two id sets by union, intersection, or difference without allocating a third set
* ask how many ids are at or below a value or inside a range, which id is the k-th smallest, or which id comes next or before
* walk a set of ids in ascending order without sorting them
* hold ids scattered across a wide range, such as row or document ids, without allocating the whole range
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `roaringBitset`kind `roaring` | you cannot name the largest id you will store, or fewer than one id in 64 of the range you can name holds a stored id | two bytes per stored id while a chunk is an array and one bit per possible id once it becomes a bitmap, plus a directory entry per occupied chunk and, once the set holds at least as many ids as its highest chunk key, a two-byte key-table entry per key; about 1.7 times slower than dense on has at half density of a 2^24 universe and about 4.7 times slower at one id in 16, and the only layout that stays small when one id is far from the rest |
| `denseBitset`kind `dense` | you can name the largest id, it sits within 64 MiB of bitmap, and per-id has and add traffic dominates the operation mix | one bit per possible id up to the largest id it has held until clear, so a single far id pays for the whole span; measured about 1.7 times faster than roaring on has at half density of a 2^24 universe, about 4.7 times faster at one id in 16, and faster at every density measured |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/bitset/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
ID span65,53616Reset
* Two exact sets share 3 IDs. The third recent ID is 7.
* One far ID needs 8192 dense bitmap bytes or 2 bytes of Roaring array payload in this model.
* Roaring converts its array container to a bitmap above 4,096 IDs. The model excludes headers and directory entries.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/bitset/demo.ts) against `knotkit/bitset` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`roaringBitset`](/reference/knotkit/bitset/functions/roaringbitset/) | `Bitset` | Bitset over 65,536-id chunks, each a sorted Uint16Array below the Roaring crossover and an 8 KB bitmap above it, so storage follows the ids stored rather than the span they occupy. |
| [`denseBitset`](/reference/knotkit/bitset/functions/densebitset/) | `Bitset` | Bitset over one flat Uint32Array bitmap that doubles on growth and keeps its high-water capacity until clear, so its storage follows the largest id it has held. |
Cost per member. Open a row for every operation.
`roaringBitset` 22 members
| Member | Cost |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `size` | O(1) |
| `has` | O(log c + log n) array container, O(log c) bitmap container; the O(log c) lookup is one indexed read once the key table is built |
| `add` | O(log c + n) array container, O(log c) bitmap container |
| `delete` | O(log c + n) array container, O(log c) bitmap container |
| `addRange` | O(chunks in span) |
| `deleteRange` | O(chunks in span) |
| `countRange` | O(log c + chunks in span) |
| `addAll` | O(k log k) to stage a generic operand, skipped when it ascends, then one merge per touched chunk; O(min c) chunk copies for a Bitset operand |
| `deleteAll` | O(k log k) to stage a generic operand, then one pass per touched chunk |
| `retainAll` | O(c + k log k) |
| `equals` | O(min c) |
| `isSubsetOf` | O(min c) |
| `isDisjointFrom` | O(min c), stops at the first shared chunk |
| `intersectionSize` | O(min c) |
| `at` | O(c), from the nearer end |
| `rank` | O(c), from the nearer end |
| `ceiling` | O(c) |
| `floor` | O(log c) |
| `values` | O(size), O(1) per step |
| `keys` | O(size), O(1) per step |
| `[Symbol.iterator]` | O(size), O(1) per step |
| `clear` | O(1) |
`denseBitset` 22 members
| Member | Cost |
| ------------------- | ----------------------------------------------------------------------------- |
| `size` | O(1) |
| `has` | O(1) |
| `add` | O(1) amortized |
| `delete` | O(1); the trailing-word trim is deferred to the next read that walks the span |
| `addRange` | O((end - start) / 32) |
| `deleteRange` | O((end - start) / 32) |
| `countRange` | O((end - start) / 32) |
| `addAll` | O(k) |
| `deleteAll` | O(k) |
| `retainAll` | O(maxId / 32 + k log k) |
| `equals` | O(min maxId / 32) |
| `isSubsetOf` | O(min maxId / 32) |
| `isDisjointFrom` | O(min maxId / 32), stops at the first shared word |
| `intersectionSize` | O(min maxId / 32) |
| `at` | O(maxId / 32), from the nearer end |
| `rank` | O(maxId / 32), from the nearer end |
| `ceiling` | O(maxId / 32) |
| `floor` | O(maxId / 32) |
| `values` | O(maxId / 32), O(1) per step |
| `keys` | O(maxId / 32), O(1) per step |
| `[Symbol.iterator]` | O(maxId / 32), O(1) per step |
| `clear` | O(1) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `BitsetInvalidInputError` or `BitsetParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `BitsetInvalidInputError`
`INVALID_ID` `INVALID_RANGE` `INVALID_INDEX` `FOREIGN_BITSET` `INVALID_OPERAND` `MAX_CAPACITY_EXCEEDED` `MODIFIED_DURING_ITERATION` `SERIALIZATION_LIMIT_EXCEEDED`
* `BitsetParseError`
`INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `INVALID_ID_SEQUENCE` `CARDINALITY_MISMATCH` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/bitset/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeBitset`, `deserializeBitset`
* Formats
binary
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| a plain set over arbitrary keys, or over ids beyond 2^32 - 1 | Set or Map |
| membership over unbounded values where a small false-positive rate is acceptable | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| read a set as it was at an earlier point while it keeps changing | [`knotkit/snapshot-set`](/modules/snapshot-set/) |
| a boolean flag per vertex you already index by number, where membership is the only question | a pre-sized Uint8Array, as problems/mst and problems/tsp do |
| track which elements are connected and merge groups | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| persist the set in a format another implementation reads | your own encoder: the binary artifact is Knotkit's own and is not RoaringFormatSpec-compatible |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/bitset/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/bitset/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#bitset).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/bitsetCopy prompt
```
Use knotkit/bitset for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/bitset'.
Exports:
- `roaringBitset` → `Bitset`: Bitset over 65,536-id chunks, each a sorted Uint16Array below the Roaring crossover and an 8 KB bitmap above it, so storage follows the ids stored rather than the span they occupy.
- `denseBitset` → `Bitset`: Bitset over one flat Uint32Array bitmap that doubles on growth and keeps its high-water capacity until clear, so its storage follows the largest id it has held.
Pick the layout by these rules:
- `roaringBitset` (kind 'roaring') when you cannot name the largest id you will store, or fewer than one id in 64 of the range you can name holds a stored id
- `denseBitset` (kind 'dense') when you can name the largest id, it sits within 64 MiB of bitmap, and per-id has and add traffic dominates the operation mix
Use something else when:
- a plain set over arbitrary keys, or over ids beyond 2^32 - 1 → Set or Map
- membership over unbounded values where a small false-positive rate is acceptable → knotkit/scalar-sketch
- read a set as it was at an earlier point while it keeps changing → knotkit/snapshot-set
- a boolean flag per vertex you already index by number, where membership is the only question → a pre-sized Uint8Array, as problems/mst and problems/tsp do
- track which elements are connected and merge groups → knotkit/disjoint-set
- persist the set in a format another implementation reads → your own encoder: the binary artifact is Knotkit's own and is not RoaringFormatSpec-compatible
Errors are BitsetInvalidInputError or BitsetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/bitset/wire` (serializeBitset, deserializeBitset).
Full page: https://knotkit.jkomyno.dev/modules/bitset.md
Types: node_modules/knotkit/bitset/ and https://knotkit.jkomyno.dev/reference/knotkit/bitset/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/bitset/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/bitset/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/bitset/knotkit.capability.json)suggest a change to the source record
# knotkit/cache
> Bounds an in-memory key-value store by entry count or total weight, with least-recently-used, SIEVE, S3-FIFO, or caller-supplied eviction and optional expiry
## Use
[Section titled “Use”](#use)
```ts
import { sieveCache } from 'knotkit/cache'
const cache = sieveCache({ capacity: 2 })
cache.set('a', 1) // []
cache.set('b', 2) // []
cache.get('a') // 1, counts as a use
cache.set('c', 3) // [{ key: 'b', value: 2 }], the entries evicted to make room
cache.peek('b') // undefined
```
cache.ts●
ResetEditRun
```
```
```ts
import { leastRecentlyUsedCache } from 'knotkit/cache'
let now = 0
const responses = leastRecentlyUsedCache({
capacity: 1_000_000, // bytes
weigh: (_key, value) => value.byteLength,
timeToLive: 60_000, // milliseconds of the clock below
clock: () => now,
})
responses.set('/a', new Uint8Array(400_000))
now = 60_000
responses.get('/a') // undefined, its age has reached timeToLive
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* keep the results of repeated lookups in memory without letting them grow past a fixed size
* bound a store by total byte size or cost instead of by number of entries
* let stored results expire after a fixed time while the clock stays under test control
* find out which entries were pushed out to make room, so they can be flushed or logged
* switch the eviction policy for a given traffic shape without changing any call site
* evict in an order of my own, such as by recompute cost or an assigned priority, while the cache keeps handling weights, expiry, and iteration
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `leastRecentlyUsedCache`kind `least-recently-used` | a key read just now is the key most likely read next, eviction must follow strict recency order, and no run of never-repeated keys is longer than capacity; on the pinned one-hit trace it keeps 19 of 50 hot keys where sieve and s3-fifo keep all 50 | one recency-list move on every get and replace; the fewest hits of the three policies on every pinned trace |
| `sieveCache`kind `sieve` | a minority of keys takes most reads, and the keys that are read repeatedly leave more than one slot of capacity free when a scan of never-repeated keys arrives; on a pinned scan of 90 hot keys in capacity 100 it keeps all 90 | one visited bit per entry and no list move on get; loses its whole hot set to a scan when that set fills all but one slot |
| `s3FifoCache`kind `s3-fifo` | one-pass scans or keys requested once are common, and the repeatedly read keys fit in the main queue, which is 90 percent of capacity; on a pinned scan of 9 hot keys in capacity 10 it keeps all 9 where the other two keep none | three queues and a ghost key for each evicted entry, retaining up to as many evicted keys as there are entries in the main queue; the slowest policy in the bench, and 152 fewer hits than sieve on the pinned Zipf 1.0 trace |
| `customCache`kind `custom` | the order entries must leave in depends on a fact none of least-recently-used, sieve, or s3-fifo reads, such as recompute cost, a caller-assigned priority, or read frequency | a wrapper call and flag check per member and a try/finally per policy callback, plus whatever the policy keeps in its own objects; with a Map-based least-recently-used policy the bench replays take 2.3 times as long as leastRecentlyUsedCache on Zipf traffic and 3.8 times on a scan |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/cache/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
Cold keys per scan1616Reset
* Replay 12 rounds with four recurring keys and 16 one-off keys per round.
* At 8 entries, SIEVE hits 41.7% of requests and least recently used hits 27.4%.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/cache/demo.ts) against `knotkit/cache` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| -------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`leastRecentlyUsedCache`](/reference/knotkit/cache/functions/leastrecentlyusedcache/) | `Cache` | Bounded cache that evicts the entry used least recently; a use moves the entry to the front of a recency list. |
| [`sieveCache`](/reference/knotkit/cache/functions/sievecache/) | `Cache` | Bounded cache that evicts with SIEVE: a hand clears visited bits from the oldest entry toward the newest and evicts the first unvisited entry. |
| [`s3FifoCache`](/reference/knotkit/cache/functions/s3fifocache/) | `Cache` | Bounded cache that evicts with S3-FIFO: a probationary queue, a main queue, and a ghost queue of recently evicted keys. |
| [`customCache`](/reference/knotkit/cache/functions/customcache/) | `Cache` | Bounded cache that evicts the key a caller-supplied CacheEvictionPolicy chooses; the policy sees keys only, is told when keys are added, used, and deleted, and its chosen victim is validated before anything is removed. |
Cost per member. Open a row for every operation.
`leastRecentlyUsedCache` 12 members
| Member | Cost |
| --------------- | -------------------------------- |
| `size` | O(1) |
| `totalWeight` | O(1) |
| `get` | O(1) average |
| `peek` | O(1) average |
| `has` | O(1) average |
| `set` | O(1) amortized per entry evicted |
| `delete` | O(1) average |
| `clear` | O(n) |
| `deleteExpired` | O(n) |
| `keys` | O(1) per step, O(n) total |
| `values` | O(1) per step, O(n) total |
| `entries` | O(1) per step, O(n) total |
`sieveCache` 12 members
| Member | Cost |
| --------------- | -------------------------------- |
| `size` | O(1) |
| `totalWeight` | O(1) |
| `get` | O(1) average |
| `peek` | O(1) average |
| `has` | O(1) average |
| `set` | O(1) amortized per entry evicted |
| `delete` | O(1) average |
| `clear` | O(n) |
| `deleteExpired` | O(n) |
| `keys` | O(1) per step, O(n) total |
| `values` | O(1) per step, O(n) total |
| `entries` | O(1) per step, O(n) total |
`s3FifoCache` 12 members
| Member | Cost |
| --------------- | -------------------------------- |
| `size` | O(1) |
| `totalWeight` | O(1) |
| `get` | O(1) average |
| `peek` | O(1) average |
| `has` | O(1) average |
| `set` | O(1) amortized per entry evicted |
| `delete` | O(1) average |
| `clear` | O(n) |
| `deleteExpired` | O(n) |
| `keys` | O(1) per step, O(n) total |
| `values` | O(1) per step, O(n) total |
| `entries` | O(1) per step, O(n) total |
`customCache` 12 members
| Member | Cost |
| --------------- | ------------------------------------------------------------------------------------------------- |
| `size` | O(1) |
| `totalWeight` | O(1) |
| `get` | O(1) average plus the policy's used |
| `peek` | O(1) average |
| `has` | O(1) average |
| `set` | O(1) average plus the policy's added or used, plus its chooseVictim and deleted per entry evicted |
| `delete` | O(1) average plus the policy's deleted |
| `clear` | O(n) plus the policy's clear |
| `deleteExpired` | O(n) plus the policy's deleted per expired entry |
| `keys` | O(1) per step, O(n) total |
| `values` | O(1) per step, O(n) total |
| `entries` | O(1) per step, O(n) total |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------- |
| time source for expiry; nothing in the cache reads the time on its own | `Clock` | [`knotkit/cache`](/modules/cache/) |
| entry weight for a total-weight capacity bound | `(key: K, value: V) => number` | `the caller` |
| eviction order for a custom cache: a factory from capacity to the callbacks added, used, deleted, chooseVictim, and optional clear | `(capacity: number) => CacheEvictionPolicy` | [`knotkit/cache`](/modules/cache/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `CacheInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_CAPACITY` `INVALID_WEIGHT` `ENTRY_TOO_HEAVY` `INVALID_VALUE` `INVALID_TIME_TO_LIVE` `MISSING_CLOCK` `INVALID_CLOCK_READING` `INVALID_VICTIM` `REENTRANT_POLICY`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| deduplicate concurrent asynchronous lookups, or compute a missing value on demand | a Map\> next to a Cache, because the cache is synchronous and stores no promises for you |
| a map that must never drop an entry | Map |
| store artifacts by the hash of their content and prove what a key returns | [`knotkit/cas`](/modules/cas/) |
| give different entries different lifetimes inside one cache | one cache per lifetime, each built with its own timeToLive |
| count how often keys occur in a stream without keeping the keys | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/cache/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/cache/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#cache).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/cacheCopy prompt
```
Use knotkit/cache for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/cache'.
Exports:
- `leastRecentlyUsedCache` → `Cache`: Bounded cache that evicts the entry used least recently; a use moves the entry to the front of a recency list.
- `sieveCache` → `Cache`: Bounded cache that evicts with SIEVE: a hand clears visited bits from the oldest entry toward the newest and evicts the first unvisited entry.
- `s3FifoCache` → `Cache`: Bounded cache that evicts with S3-FIFO: a probationary queue, a main queue, and a ghost queue of recently evicted keys.
- `customCache` → `Cache`: Bounded cache that evicts the key a caller-supplied CacheEvictionPolicy chooses; the policy sees keys only, is told when keys are added, used, and deleted, and its chosen victim is validated before anything is removed.
Pick the layout by these rules:
- `leastRecentlyUsedCache` (kind 'least-recently-used') when a key read just now is the key most likely read next, eviction must follow strict recency order, and no run of never-repeated keys is longer than capacity; on the pinned one-hit trace it keeps 19 of 50 hot keys where sieve and s3-fifo keep all 50
- `sieveCache` (kind 'sieve') when a minority of keys takes most reads, and the keys that are read repeatedly leave more than one slot of capacity free when a scan of never-repeated keys arrives; on a pinned scan of 90 hot keys in capacity 100 it keeps all 90
- `s3FifoCache` (kind 's3-fifo') when one-pass scans or keys requested once are common, and the repeatedly read keys fit in the main queue, which is 90 percent of capacity; on a pinned scan of 9 hot keys in capacity 10 it keeps all 9 where the other two keep none
- `customCache` (kind 'custom') when the order entries must leave in depends on a fact none of least-recently-used, sieve, or s3-fifo reads, such as recompute cost, a caller-assigned priority, or read frequency
Inputs and their sources:
- time source for expiry; nothing in the cache reads the time on its own: `Clock` from `knotkit/cache`
- entry weight for a total-weight capacity bound: `(key: K, value: V) => number` from `the caller`
- eviction order for a custom cache: a factory from capacity to the callbacks added, used, deleted, chooseVictim, and optional clear: `(capacity: number) => CacheEvictionPolicy` from `knotkit/cache`
Use something else when:
- deduplicate concurrent asynchronous lookups, or compute a missing value on demand → a Map> next to a Cache, because the cache is synchronous and stores no promises for you
- a map that must never drop an entry → Map
- store artifacts by the hash of their content and prove what a key returns → knotkit/cas
- give different entries different lifetimes inside one cache → one cache per lifetime, each built with its own timeToLive
- count how often keys occur in a stream without keeping the keys → knotkit/scalar-sketch
Errors are CacheInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/cache.md
Types: node_modules/knotkit/cache/ and https://knotkit.jkomyno.dev/reference/knotkit/cache/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/cache/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/cache/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/cache/knotkit.capability.json)suggest a change to the source record
# knotkit/cas
> Addresses wire-envelope artifacts by content hash and stores them through an injected backend
## Use
[Section titled “Use”](#use)
```ts
import { contentAddressedStore } from 'knotkit/cas'
import { xxh64 } from 'knotkit/hash'
const blobs = new Map()
const hasher = xxh64()
const store = contentAddressedStore({
// Any object with has/get/set works: a Map, S3 client, or fetch-backed store.
backend: {
has: async (address) => blobs.has(address),
get: async (address) => blobs.get(address),
set: async (address, bytes) => void blobs.set(address, bytes),
},
// Injected, so the address can be reproduced by every reader that shares it.
hash: (bytes) => hasher.encodeHex(hasher.bytes(bytes)),
// One store addresses one family of artifacts.
magic: Uint8Array.of(0x4b, 0x4b, 0x48, 0x50),
})
const artifact = {
payloadVersion: 1,
packageHeader: Uint8Array.of(1, 0, 0, 0),
sections: [{ tag: 1, bytes: new Uint8Array([1, 2, 3]) }],
}
const address = await store.add(artifact)
address // a 16-character hex address for these exact bytes
await store.add(artifact) // one stored copy: the address is already present
const envelope = await store.get(address) // re-hashed, then decoded
```
cas.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* store the same artifact once no matter how many callers write it
* prove that the bytes a store returned are the content a key names
* share artifacts between processes that do not share a filesystem
* keep serialized structures in an object store, a browser cache, or a Map behind one interface
## Worked example
[Section titled “Worked example”](#worked-example)
* 12 writes requested, 3 distinct blobs stored.
* Reading 558718ba60ab8ed6 verifies its address and returns payload 1.
* Identical artifact bytes share one address and one backend entry.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/cas/demo.ts) against `knotkit/cas`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ---------------------------------------------------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------- |
| [`contentAddressedStore`](/reference/knotkit/cas/functions/contentaddressedstore/) | `ContentAddressedStore` | Bind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store. |
Cost per member. Open a row for every operation.
`contentAddressedStore` 4 members
| Member | Cost |
| ----------- | ------------- |
| `addressOf` | O(n) |
| `add` | O(n) |
| `has` | O(1) expected |
| `get` | O(n) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ----------------------------------------- | ------------------------------- | ------------------------------- |
| content hash from framed bytes to address | `(bytes: Uint8Array) => string` | `knotkit/hash or crypto.subtle` |
| durable storage | `ArtifactBackend` | `the caller's backend` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `CasInvalidInputError` or `CasParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `CasInvalidInputError`
`INVALID_ARTIFACT`
* `CasParseError`
`INVALID_ADDRESS` `INVALID_HASH` `HASH_FAILURE` `BACKEND_FAILURE` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `UNKNOWN_KIND` `ADDRESS_MISMATCH` `ADDRESS_COLLISION`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
| persist a structure to local disk in one process | the structure package's serialize function and the platform file API |
| an artifact that must be readable without the hash that produced its key | a caller-chosen storage key and an envelope from knotkit/wire |
| cryptographic collision resistance or signed artifacts | crypto.subtle with SHA-256, or signature verification over the envelope bytes |
| a cache with eviction, expiry, or least-recently-used ordering | [`knotkit/cache`](/modules/cache/) |
| mutable blobs whose key stays stable as content changes | a plain key-value backend; a content address changes with the content |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/cas/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/cas/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/casCopy prompt
```
Use knotkit/cas for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/cas'.
Exports:
- `contentAddressedStore` → `ContentAddressedStore`: Bind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store.
Inputs and their sources:
- content hash from framed bytes to address: `(bytes: Uint8Array) => string` from `knotkit/hash or crypto.subtle`
- durable storage: `ArtifactBackend` from `the caller's backend`
Use something else when:
- persist a structure to local disk in one process → the structure package's serialize function and the platform file API
- an artifact that must be readable without the hash that produced its key → a caller-chosen storage key and an envelope from knotkit/wire
- cryptographic collision resistance or signed artifacts → crypto.subtle with SHA-256, or signature verification over the envelope bytes
- a cache with eviction, expiry, or least-recently-used ordering → knotkit/cache
- mutable blobs whose key stays stable as content changes → a plain key-value backend; a content address changes with the content
Errors are CasInvalidInputError or CasParseError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/cas.md
Types: node_modules/knotkit/cas/ and https://knotkit.jkomyno.dev/reference/knotkit/cas/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/cas/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/cas/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/cas/knotkit.capability.json)suggest a change to the source record
# knotkit/combinatorics
> Counts permutations, combinations, cycles, and set partitions exactly or in log space
## Use
[Section titled “Use”](#use)
```ts
import { logBinomialCoefficient, stirlingFirstKindRow, stirlingSecondKind } from 'knotkit/combinatorics'
stirlingFirstKindRow(4) // [0n, 6n, 11n, 6n, 1n]
stirlingSecondKind(4, 2) // 7n partitions into two blocks
logBinomialCoefficient(1e15, 1) // 34.538776394910684
```
combinatorics.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* count permutations or unordered combinations exactly
* compute Stirling numbers for permutations by cycle count and partitions by block count
* compute Bell numbers to count all set partitions
* evaluate log-factorials and log binomial coefficients for large inputs
## Worked example
[Section titled “Worked example”](#worked-example)
* 20 items give 2432902008176640000 permutations, 51724158235372 partitions, or 184756 subsets of size 10.
* Use the exact BigInt functions for counts and the log functions when you only need their magnitude.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/combinatorics/demo.ts) against `knotkit/combinatorics`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ---------------------------------------------------------------------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------- |
| [`factorial`](/reference/knotkit/combinatorics/functions/factorial/) | `bigint` | Permutations of all n items. |
| [`logFactorial`](/reference/knotkit/combinatorics/functions/logfactorial/) | `number` | Natural logarithm of n factorial for any non-negative safe integer n. |
| [`binomialCoefficient`](/reference/knotkit/combinatorics/functions/binomialcoefficient/) | `bigint` | Combinations of k from n items. |
| [`logBinomialCoefficient`](/reference/knotkit/combinatorics/functions/logbinomialcoefficient/) | `number` | Natural logarithm of the number of combinations of k from n items, including when n is far larger than k. |
| [`stirlingFirstKind`](/reference/knotkit/combinatorics/functions/stirlingfirstkind/) | `bigint` | Permutations of n items with k cycles, the unsigned Stirling number of the first kind. |
| [`stirlingFirstKindRow`](/reference/knotkit/combinatorics/functions/stirlingfirstkindrow/) | `readonly bigint[]` | Permutations of n items for each cycle count from 0 to n. |
| [`logStirlingFirstKind`](/reference/knotkit/combinatorics/functions/logstirlingfirstkind/) | `number` | Natural logarithm of the number of permutations with k cycles. |
| [`stirlingSecondKind`](/reference/knotkit/combinatorics/functions/stirlingsecondkind/) | `bigint` | Partitions of n items into k non-empty blocks. |
| [`stirlingSecondKindRow`](/reference/knotkit/combinatorics/functions/stirlingsecondkindrow/) | `readonly bigint[]` | Partitions of n items for each non-empty block count from 0 to n. |
| [`logStirlingSecondKind`](/reference/knotkit/combinatorics/functions/logstirlingsecondkind/) | `number` | Natural logarithm of the number of partitions into k non-empty blocks. |
| [`bellNumber`](/reference/knotkit/combinatorics/functions/bellnumber/) | `bigint` | Set partitions across all block counts. |
| [`logBellNumber`](/reference/knotkit/combinatorics/functions/logbellnumber/) | `number` | Natural logarithm of the number of set partitions across all block counts. |
Cost per member. Open a row for every operation.
`factorial` 1 members
| Member | Cost |
| --------- | -------------------- |
| `compute` | O(n) multiplications |
`logFactorial` 1 members
| Member | Cost |
| --------- | ---- |
| `compute` | O(1) |
`binomialCoefficient` 1 members
| Member | Cost |
| --------- | ------------------------------------------------- |
| `compute` | O(min(k, n - k)) arithmetic operations for k <= n |
`logBinomialCoefficient` 1 members
| Member | Cost |
| --------- | ---- |
| `compute` | O(1) |
`stirlingFirstKind` 1 members
| Member | Cost |
| --------- | -------------------------------------- |
| `compute` | O(nk) arithmetic operations for k <= n |
`stirlingFirstKindRow` 1 members
| Member | Cost |
| --------- | --------------------------------------------------- |
| `compute` | O(n²) arithmetic operations and O(n) bigint storage |
`logStirlingFirstKind` 1 members
| Member | Cost |
| --------- | -------------------------------------- |
| `compute` | O(nk) arithmetic operations for k <= n |
`stirlingSecondKind` 1 members
| Member | Cost |
| --------- | -------------------------------------- |
| `compute` | O(nk) arithmetic operations for k <= n |
`stirlingSecondKindRow` 1 members
| Member | Cost |
| --------- | --------------------------------------------------- |
| `compute` | O(n²) arithmetic operations and O(n) bigint storage |
`logStirlingSecondKind` 1 members
| Member | Cost |
| --------- | -------------------------------------- |
| `compute` | O(nk) arithmetic operations for k <= n |
`bellNumber` 1 members
| Member | Cost |
| --------- | --------------------------------------- |
| `compute` | O(n²) additions and O(n) bigint storage |
`logBellNumber` 1 members
| Member | Cost |
| --------- | --------------------------------------- |
| `compute` | O(n²) additions and O(n) bigint storage |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `CombinatoricsInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_COUNT` `COUNT_TOO_LARGE`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------ | -------------------------------------------------------- |
| list the permutations or combinations themselves | a generator that enumerates permutations or combinations |
| simulate selecting items without replacement | [`knotkit/sampling`](/modules/sampling/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/combinatorics/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/combinatorics/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/combinatoricsCopy prompt
```
Use knotkit/combinatorics for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/combinatorics'.
Exports:
- `factorial` → `bigint`: Permutations of all n items.
- `logFactorial` → `number`: Natural logarithm of n factorial for any non-negative safe integer n.
- `binomialCoefficient` → `bigint`: Combinations of k from n items.
- `logBinomialCoefficient` → `number`: Natural logarithm of the number of combinations of k from n items, including when n is far larger than k.
- `stirlingFirstKind` → `bigint`: Permutations of n items with k cycles, the unsigned Stirling number of the first kind.
- `stirlingFirstKindRow` → `readonly bigint[]`: Permutations of n items for each cycle count from 0 to n.
- `logStirlingFirstKind` → `number`: Natural logarithm of the number of permutations with k cycles.
- `stirlingSecondKind` → `bigint`: Partitions of n items into k non-empty blocks.
- `stirlingSecondKindRow` → `readonly bigint[]`: Partitions of n items for each non-empty block count from 0 to n.
- `logStirlingSecondKind` → `number`: Natural logarithm of the number of partitions into k non-empty blocks.
- `bellNumber` → `bigint`: Set partitions across all block counts.
- `logBellNumber` → `number`: Natural logarithm of the number of set partitions across all block counts.
Use something else when:
- list the permutations or combinations themselves → a generator that enumerates permutations or combinations
- simulate selecting items without replacement → knotkit/sampling
Errors are CombinatoricsInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/combinatorics.md
Types: node_modules/knotkit/combinatorics/ and https://knotkit.jkomyno.dev/reference/knotkit/combinatorics/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/combinatorics/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/combinatorics/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/combinatorics/knotkit.capability.json)suggest a change to the source record
# knotkit/deque
> Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
## Use
[Section titled “Use”](#use)
```ts
import { arrayDeque } from 'knotkit/deque'
const frontier = arrayDeque({ items: ['parse', 'layout'] })
frontier.pushBack('render')
frontier.popFront() // 'parse'
frontier.popFront() // 'layout'
frontier.popFront() // 'render'
```
deque.ts●
ResetEditRun
```
```
```ts
import { float64ArrayDeque } from 'knotkit/deque'
const window = float64ArrayDeque({ capacity: 60 })
let sum = 0
function observe(value: number): number {
sum += value
const evicted = window.pushBack(value) // undefined until the window is full
if (evicted !== undefined) sum -= evicted
return sum / window.size
}
```
```ts
const readings = arrayDeque({ capacity: 5 })
for (const reading of stream) readings.pushBack(reading ?? null) // reading: number | undefined
const last = [...readings].map((value) => value ?? undefined)
```
```ts
const second = recent.size >= 2 ? recent.at(-2) : undefined
```
```ts
const recent = arrayDeque({ items: ['a', 'b', 'c'] })
recent.at(0) // 'a'
recent.at(-1) // 'c'
for (const item of recent) console.log(item)
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* take items out in the order they arrived without Array.prototype.shift turning the loop quadratic
* add and remove items at both ends of a sequence, such as a breadth-first and depth-first hybrid
* keep only the last N values of a stream and learn which value just fell out, for a running sum or moving average
* hold a long numeric buffer in eight bytes per value with no per-element allocation
* read the k-th item from either end of a queue without removing anything
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| --------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `arrayDeque`kind `array` | any element is not a number, such as an object, a string, or null | one boxed slot per element and a slot write on every pop to release it; on the pinned 100,000-element first-in first-out bench it takes 2.6 times as long as float64-array |
| `float64ArrayDeque`kind `float64-array` | every element is a number, including NaN and -0 | stores numbers only and rejects anything else with INVALID_VALUE; eight bytes per slot whether or not the value is an integer |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/deque/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
Window (readings)55Reset
* Mean over the last 5 readings: 13.40.
* Both layouts retain the last 5 values: 13, 14, 12, 15, 13.
* Each push returns the outgoing value once the window is full.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/deque/demo.ts) against `knotkit/deque` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ---------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`arrayDeque`](/reference/knotkit/deque/functions/arraydeque/) | `Deque` | Double-ended queue over a plain array ring buffer for any element type except undefined; an optional capacity evicts from the opposite end and returns the evicted element. |
| [`float64ArrayDeque`](/reference/knotkit/deque/functions/float64arraydeque/) | `Deque` | Double-ended queue of numbers over a Float64Array ring buffer, eight bytes per slot; an optional capacity evicts from the opposite end and returns the evicted element. |
Cost per member. Open a row for every operation.
`arrayDeque` 12 members
| Member | Cost |
| ------------------- | ------------------------- |
| `size` | O(1) |
| `capacity` | O(1) |
| `pushBack` | O(1) amortized |
| `pushFront` | O(1) amortized |
| `popBack` | O(1) |
| `popFront` | O(1) |
| `peekBack` | O(1) |
| `peekFront` | O(1) |
| `at` | O(1) |
| `clear` | O(1) |
| `values` | O(1) per step, O(n) total |
| `[Symbol.iterator]` | O(1) per step, O(n) total |
`float64ArrayDeque` 12 members
| Member | Cost |
| ------------------- | ------------------------- |
| `size` | O(1) |
| `capacity` | O(1) |
| `pushBack` | O(1) amortized |
| `pushFront` | O(1) amortized |
| `popBack` | O(1) |
| `popFront` | O(1) |
| `peekBack` | O(1) |
| `peekFront` | O(1) |
| `at` | O(1) |
| `clear` | O(1) |
| `values` | O(1) per step, O(n) total |
| `[Symbol.iterator]` | O(1) per step, O(n) total |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `DequeInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `EMPTY` `INVALID_CAPACITY` `INVALID_VALUE` `INVALID_INDEX` `MAX_CAPACITY_EXCEEDED` `MODIFIED_DURING_ITERATION`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| always take the smallest or largest item rather than the oldest or newest | [`knotkit/heap`](/modules/heap/) |
| evict entries by key, recency of use, or total weight | [`knotkit/cache`](/modules/cache/) |
| insert or remove items in the middle, or overwrite an item by index | Array with splice, or a linked list |
| a stack used at one end only | Array push and pop, which are already O(1) |
| a bounded forward-only scan whose maximum size is known, such as a breadth-first walk over n vertices | a pre-sized Int32Array or Float64Array with head and tail cursors, indexed by two integers that only move forward; it never wraps or grows, so a deque only adds cost |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/deque/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/deque/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#deque).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/dequeCopy prompt
```
Use knotkit/deque for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/deque'.
Exports:
- `arrayDeque` → `Deque`: Double-ended queue over a plain array ring buffer for any element type except undefined; an optional capacity evicts from the opposite end and returns the evicted element.
- `float64ArrayDeque` → `Deque`: Double-ended queue of numbers over a Float64Array ring buffer, eight bytes per slot; an optional capacity evicts from the opposite end and returns the evicted element.
Pick the layout by these rules:
- `arrayDeque` (kind 'array') when any element is not a number, such as an object, a string, or null
- `float64ArrayDeque` (kind 'float64-array') when every element is a number, including NaN and -0
Use something else when:
- always take the smallest or largest item rather than the oldest or newest → knotkit/heap
- evict entries by key, recency of use, or total weight → knotkit/cache
- insert or remove items in the middle, or overwrite an item by index → Array with splice, or a linked list
- a stack used at one end only → Array push and pop, which are already O(1)
- a bounded forward-only scan whose maximum size is known, such as a breadth-first walk over n vertices → a pre-sized Int32Array or Float64Array with head and tail cursors, indexed by two integers that only move forward; it never wraps or grows, so a deque only adds cost
Errors are DequeInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/deque.md
Types: node_modules/knotkit/deque/ and https://knotkit.jkomyno.dev/reference/knotkit/deque/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/deque/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/deque/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/deque/knotkit.capability.json)suggest a change to the source record
# knotkit/disjoint-set
> Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts
## Use
[Section titled “Use”](#use)
```ts
import { indexedDisjointSet } from 'knotkit/disjoint-set'
const components = indexedDisjointSet(4) // elements 0, 1, 2, 3
components.unite(0, 1)
components.unite(1, 2)
components.areConnected(0, 2) // true
components.areConnected(0, 3) // false
components.setCount // 2
```
disjoint-set.ts●
ResetEditRun
```
```
```ts
import { objectDisjointSet } from 'knotkit/disjoint-set'
const network = objectDisjointSet(['a', 'b', 'c', 'd'])
network.unite('a', 'b') // true, two sets became one
network.unite('b', 'c') // true
network.unite('a', 'c') // false, they were already connected
network.areConnected('a', 'd') // false
network.sets() // Map { 'a' => ['a', 'b', 'c'], 'd' => ['d'] }
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* tell whether two items are already connected, while connections keep arriving one at a time
* merge two groups of items into one, pair by pair, and count how many groups remain
* run Kruskal's minimum spanning tree, or detect a cycle in an undirected graph
* group a large collection of items into its connected components
* drive percolation, image segmentation, or any equivalence relation that only ever grows by merging
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `indexedDisjointSet`kind `indexed` | every element is a dense integer in \`0..size - 1\`, or \`append\` can mint the next one, so no value-to-index registry is needed; at 100,000 elements each measured workload runs 4.2x to 138x faster than the generic layouts | 5 bytes of typed-array storage per initial element and no per-element Map entry; \`append\` grows geometrically and can reserve up to twice the current size |
| `objectDisjointSet`kind `object` | identifiers are arbitrary, sparse, or non-numeric, and a node object per element is worth inspecting while debugging; the object and struct-of-arrays layouts stay within the same order of magnitude at 100,000 elements | 5 bytes of node storage plus one Map entry per element, and one heap object allocation per element |
| `structOfArraysDisjointSet`kind `struct-of-arrays` | identifiers are arbitrary, sparse, or non-numeric, n is at or above 100,000, and no per-element node object is ever read | 5 bytes of node storage plus one Map entry and one array slot per element, with typed-array growth on insert |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/disjoint-set/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
* 10 edges: 7 connected separate components, 3 joined already-connected nodes.
* Remaining components across indexed, object, and struct-of-arrays: 1, 1, 1.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/disjoint-set/demo.ts) against `knotkit/disjoint-set`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`indexedDisjointSet`](/reference/knotkit/disjoint-set/functions/indexeddisjointset/) | `IndexedDisjointSet` | Dense integer disjoint set over \`0..size - 1\`: parent and rank in typed arrays, no element-to-index registry; \`append\` mints the next index. |
| [`objectDisjointSet`](/reference/knotkit/disjoint-set/functions/objectdisjointset/) | `GrowableDisjointSet` | Growable disjoint set over any values, keeping one \`{ parent, rank }\` object per element and a registry from value to dense index. |
| [`structOfArraysDisjointSet`](/reference/knotkit/disjoint-set/functions/structofarraysdisjointset/) | `GrowableDisjointSet` | Growable disjoint set over any values, keeping parent and rank in typed arrays behind the same value-to-index registry. |
Cost per member. Open a row for every operation.
`indexedDisjointSet` 9 members
| Member | Cost |
| -------------- | ------------------------- |
| `size` | O(1) |
| `setCount` | O(1) |
| `has` | O(1) |
| `unite` | O(alpha(n)) amortized |
| `areConnected` | O(alpha(n)) amortized |
| `find` | O(alpha(n)) amortized |
| `elements` | O(1) per step, O(n) total |
| `sets` | O(n \* alpha(n)) |
| `append` | O(1) amortized |
`objectDisjointSet` 9 members
| Member | Cost |
| -------------- | ------------------------- |
| `size` | O(1) |
| `setCount` | O(1) |
| `has` | O(1) average |
| `unite` | O(alpha(n)) amortized |
| `areConnected` | O(alpha(n)) amortized |
| `find` | O(alpha(n)) amortized |
| `elements` | O(1) per step, O(n) total |
| `sets` | O(n \* alpha(n)) |
| `add` | O(1) amortized |
`structOfArraysDisjointSet` 9 members
| Member | Cost |
| -------------- | ------------------------- |
| `size` | O(1) |
| `setCount` | O(1) |
| `has` | O(1) average |
| `unite` | O(alpha(n)) amortized |
| `areConnected` | O(alpha(n)) amortized |
| `find` | O(alpha(n)) amortized |
| `elements` | O(1) per step, O(n) total |
| `sets` | O(n \* alpha(n)) |
| `add` | O(1) amortized |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ------------------------------------------------------------------------------------------ | -------------------------------- | -------------------------------- |
| element encoding for a binary artifact of a generic layout, which no artifact carries back | `ElementCodec` | [`knotkit/wire`](/modules/wire/) |
| element validation for a JSON artifact, whose projections carry no element types | `(value: unknown) => value is T` | `the caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `DisjointSetInvalidInputError` or `DisjointSetParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `DisjointSetInvalidInputError`
`ELEMENT_ALREADY_REGISTERED` `SIZE_OUT_OF_RANGE`
* `DisjointSetParseError`
`ELEMENT_NOT_FOUND` `MAX_SIZE_EXCEEDED` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_ELEMENTS` `INVALID_LABELS` `INVALID_INDEXED_ELEMENT` `INVALID_ELEMENT` `ELEMENTS_LABELS_LENGTH_MISMATCH` `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` `DUPLICATE_ELEMENT`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/disjoint-set/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeDisjointSet`, `deserializeDisjointSet`, `serializeDisjointSetJson`, `deserializeDisjointSetJson`
* Formats
binary, json
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| look up a value by key, or check whether a single value is present | Set, Map |
| sort edges by weight before merging them one by one | Array.prototype.sort with a comparator |
| read membership as it was at an earlier moment while the set keeps changing | [`knotkit/snapshot-set`](/modules/snapshot-set/) |
| split a group apart, or undo a merge | rebuild the structure from the unions you kept, because a merge is never undone |
| walk a graph's adjacency, or find the shortest path | [`knotkit/graph`](/modules/graph/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/disjoint-set/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/disjoint-set/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#disjoint-set).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/disjoint-setCopy prompt
```
Use knotkit/disjoint-set for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/disjoint-set'.
Exports:
- `indexedDisjointSet` → `IndexedDisjointSet`: Dense integer disjoint set over `0..size - 1`: parent and rank in typed arrays, no element-to-index registry; `append` mints the next index.
- `objectDisjointSet` → `GrowableDisjointSet`: Growable disjoint set over any values, keeping one `{ parent, rank }` object per element and a registry from value to dense index.
- `structOfArraysDisjointSet` → `GrowableDisjointSet`: Growable disjoint set over any values, keeping parent and rank in typed arrays behind the same value-to-index registry.
Pick the layout by these rules:
- `indexedDisjointSet` (kind 'indexed') when every element is a dense integer in `0..size - 1`, or `append` can mint the next one, so no value-to-index registry is needed; at 100,000 elements each measured workload runs 4.2x to 138x faster than the generic layouts
- `objectDisjointSet` (kind 'object') when identifiers are arbitrary, sparse, or non-numeric, and a node object per element is worth inspecting while debugging; the object and struct-of-arrays layouts stay within the same order of magnitude at 100,000 elements
- `structOfArraysDisjointSet` (kind 'struct-of-arrays') when identifiers are arbitrary, sparse, or non-numeric, n is at or above 100,000, and no per-element node object is ever read
Inputs and their sources:
- element encoding for a binary artifact of a generic layout, which no artifact carries back: `ElementCodec` from `knotkit/wire`
- element validation for a JSON artifact, whose projections carry no element types: `(value: unknown) => value is T` from `the caller`
Use something else when:
- look up a value by key, or check whether a single value is present → Set, Map
- sort edges by weight before merging them one by one → Array.prototype.sort with a comparator
- read membership as it was at an earlier moment while the set keeps changing → knotkit/snapshot-set
- split a group apart, or undo a merge → rebuild the structure from the unions you kept, because a merge is never undone
- walk a graph's adjacency, or find the shortest path → knotkit/graph
Errors are DisjointSetInvalidInputError or DisjointSetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/disjoint-set/wire` (serializeDisjointSet, deserializeDisjointSet, serializeDisjointSetJson, deserializeDisjointSetJson).
Full page: https://knotkit.jkomyno.dev/modules/disjoint-set.md
Types: node_modules/knotkit/disjoint-set/ and https://knotkit.jkomyno.dev/reference/knotkit/disjoint-set/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/disjoint-set/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/disjoint-set/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/disjoint-set/knotkit.capability.json)suggest a change to the source record
# knotkit/distance
> Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees
## Use
[Section titled “Use”](#use)
```ts
import { DISTANCE_RULES, jaccardDistance, totalVariationDistance } from 'knotkit/distance'
const distance = jaccardDistance(new Set(['a', 'b']), new Set(['b', 'c']))
// 2 / 3
const rule = DISTANCE_RULES['kullback-leibler-divergence']
const nats = rule.compare([1, 0], [0.5, 0.5])
// Math.log(2)
const eventGap = totalVariationDistance([0.75, 0.25], [0.5, 0.5])
// 0.25, or 25 percentage points
```
distance.ts●
ResetEditRun
```
```
```ts
import { DISTANCE_KINDS, DISTANCE_RULES } from 'knotkit/distance'
const scores = DISTANCE_KINDS.flatMap((kind) => {
const rule = DISTANCE_RULES[kind]
if (rule.inputDomain === 'numeric-vector' && rule.triangleInequality === true) {
return [{ kind, score: rule.compare([0, 0], [3, 4]) }]
}
return []
})
// [{ kind: 'manhattan', score: 7 }, { kind: 'euclidean', score: 5 }]
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* rank vector differences by coordinate magnitude or angle
* measure the extra information cost of approximating one probability distribution with another
* bound how much any event probability can change between two probability distributions
* compute exact set overlap or set distance
* look up which direction to rank a comparison and whether it is symmetric or follows the triangle inequality
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
| `manhattanDistance`kind `manhattan` | cost accumulates along coordinate axes | O(n) time and O(1) extra space |
| `euclideanDistance`kind `euclidean` | you need straight-line distance or a Euclidean metric | O(n) time and O(1) extra space |
| `squaredEuclideanDistance`kind `squared-euclidean` | you need squared errors or Euclidean rankings without a square root | O(n) time and O(1) extra space |
| `meanSquaredError`kind `mean-squared-error` | loss must average squared coordinate errors | O(n) time and O(1) extra space |
| `cosineSimilarity`kind `cosine-similarity` | a higher score should mean closer vector directions | O(n) time and O(1) extra space |
| `cosineDistance`kind `cosine-distance` | a lower score should mean closer vector directions | O(n) time and O(1) extra space |
| `kullbackLeiblerDivergence`kind `kullback-leibler-divergence` | the inputs are aligned probability vectors and exchanging them can change the result | O(n) time and O(1) extra space |
| `totalVariationDistance`kind `total-variation-distance` | the inputs are aligned probability vectors and you need the largest absolute difference in event probability | O(n) time and O(1) extra space |
| `jaccardSimilarity`kind `jaccard-similarity` | you have both sets and a higher score should mean greater overlap | O(min(a.size, b.size)) membership checks and O(1) extra space |
| `jaccardDistance`kind `jaccard-distance` | you have both sets and need an overlap distance that obeys the triangle inequality | O(min(a.size, b.size)) membership checks and O(1) extra space |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/distance/README.md#performance)
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [`manhattanDistance`](/reference/knotkit/distance/functions/manhattandistance/) | `number` | Sum of absolute coordinate differences. |
| [`euclideanDistance`](/reference/knotkit/distance/functions/euclideandistance/) | `number` | Straight-line distance with a scaled sum of squares. |
| [`squaredEuclideanDistance`](/reference/knotkit/distance/functions/squaredeuclideandistance/) | `number` | Sum of squared coordinate differences. |
| [`meanSquaredError`](/reference/knotkit/distance/functions/meansquarederror/) | `number` | Mean of squared coordinate differences. |
| [`cosineSimilarity`](/reference/knotkit/distance/functions/cosinesimilarity/) | `number` | Cosine of the angle between nonzero vectors. |
| [`cosineDistance`](/reference/knotkit/distance/functions/cosinedistance/) | `number` | One minus cosine similarity, computed from unit differences. |
| [`kullbackLeiblerDivergence`](/reference/knotkit/distance/functions/kullbackleiblerdivergence/) | `number` | Directional discrete relative entropy in nats, with infinity for missing support. |
| [`totalVariationDistance`](/reference/knotkit/distance/functions/totalvariationdistance/) | `number` | Largest absolute difference in event probability between aligned probability vectors. |
| [`jaccardSimilarity`](/reference/knotkit/distance/functions/jaccardsimilarity/) | `number` | Exact fraction of the union also in the intersection. |
| [`jaccardDistance`](/reference/knotkit/distance/functions/jaccarddistance/) | `number` | Exact fraction of the union present in only one set. |
| [`jaccardOverlap`](/reference/knotkit/distance/functions/jaccardoverlap/) | `JaccardOverlap` | Return exact intersection and union counts and the corresponding Jaccard similarity in one pass. |
| [`uncheckedEuclideanDistance2D`](/reference/knotkit/distance/functions/uncheckedeuclideandistance2d/) | `number` | Straight-line distance between two points with caller-validated finite coordinates. |
| [`uncheckedSquaredEuclideanDistance`](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance/) | `number` | Sum squared differences in coordinate order over a caller-validated window, with an optional offset into the second vector. |
| [`uncheckedSquaredEuclideanDistance2D`](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance2d/) | `number` | Sum squared differences between two caller-validated planar points in ordinary binary64 arithmetic. |
Cost per member. Open a row for every operation.
`manhattanDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`euclideanDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`squaredEuclideanDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`meanSquaredError` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`cosineSimilarity` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`cosineDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`kullbackLeiblerDivergence` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`totalVariationDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`jaccardSimilarity` 1 members
| Member | Cost |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |
`jaccardDistance` 1 members
| Member | Cost |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |
`jaccardOverlap` 1 members
| Member | Cost |
| --------- | ------------------------------------------------------------- |
| `compare` | O(min(a.size, b.size)) membership checks and O(1) extra space |
`uncheckedEuclideanDistance2D` 1 members
| Member | Cost |
| --------- | ------------------- |
| `compare` | O(1) time and space |
`uncheckedSquaredEuclideanDistance` 1 members
| Member | Cost |
| --------- | ------------------------------ |
| `compare` | O(n) time and O(1) extra space |
`uncheckedSquaredEuclideanDistance2D` 1 members
| Member | Cost |
| --------- | ------------------- |
| `compare` | O(1) time and space |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `DistanceInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_DIMENSION` `NON_FINITE_COORDINATE` `ZERO_VECTOR` `INVALID_PROBABILITIES`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------- | ------------------------------------------------------ |
| estimate overlap when only set signatures fit in memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| find least-cost paths between graph vertices | [`knotkit/graph`](/modules/graph/) |
| test whether samples plausibly came from a given distribution | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/distance/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/distance/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/distanceCopy prompt
```
Use knotkit/distance for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/distance'.
Exports:
- `manhattanDistance` → `number`: Sum of absolute coordinate differences.
- `euclideanDistance` → `number`: Straight-line distance with a scaled sum of squares.
- `squaredEuclideanDistance` → `number`: Sum of squared coordinate differences.
- `meanSquaredError` → `number`: Mean of squared coordinate differences.
- `cosineSimilarity` → `number`: Cosine of the angle between nonzero vectors.
- `cosineDistance` → `number`: One minus cosine similarity, computed from unit differences.
- `kullbackLeiblerDivergence` → `number`: Directional discrete relative entropy in nats, with infinity for missing support.
- `totalVariationDistance` → `number`: Largest absolute difference in event probability between aligned probability vectors.
- `jaccardSimilarity` → `number`: Exact fraction of the union also in the intersection.
- `jaccardDistance` → `number`: Exact fraction of the union present in only one set.
- `jaccardOverlap` → `JaccardOverlap`: Return exact intersection and union counts and the corresponding Jaccard similarity in one pass.
- `uncheckedEuclideanDistance2D` → `number`: Straight-line distance between two points with caller-validated finite coordinates.
- `uncheckedSquaredEuclideanDistance` → `number`: Sum squared differences in coordinate order over a caller-validated window, with an optional offset into the second vector.
- `uncheckedSquaredEuclideanDistance2D` → `number`: Sum squared differences between two caller-validated planar points in ordinary binary64 arithmetic.
Pick the layout by these rules:
- `manhattanDistance` (kind 'manhattan') when cost accumulates along coordinate axes
- `euclideanDistance` (kind 'euclidean') when you need straight-line distance or a Euclidean metric
- `squaredEuclideanDistance` (kind 'squared-euclidean') when you need squared errors or Euclidean rankings without a square root
- `meanSquaredError` (kind 'mean-squared-error') when loss must average squared coordinate errors
- `cosineSimilarity` (kind 'cosine-similarity') when a higher score should mean closer vector directions
- `cosineDistance` (kind 'cosine-distance') when a lower score should mean closer vector directions
- `kullbackLeiblerDivergence` (kind 'kullback-leibler-divergence') when the inputs are aligned probability vectors and exchanging them can change the result
- `totalVariationDistance` (kind 'total-variation-distance') when the inputs are aligned probability vectors and you need the largest absolute difference in event probability
- `jaccardSimilarity` (kind 'jaccard-similarity') when you have both sets and a higher score should mean greater overlap
- `jaccardDistance` (kind 'jaccard-distance') when you have both sets and need an overlap distance that obeys the triangle inequality
Use something else when:
- estimate overlap when only set signatures fit in memory → knotkit/scalar-sketch
- find least-cost paths between graph vertices → knotkit/graph
- test whether samples plausibly came from a given distribution → knotkit/hypothesis-test
Errors are DistanceInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/distance.md
Types: node_modules/knotkit/distance/ and https://knotkit.jkomyno.dev/reference/knotkit/distance/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/distance/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/distance/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/distance/knotkit.capability.json)suggest a change to the source record
# knotkit/distribution
> Computes probabilities, quantiles, moments, and seeded draws for named and caller-defined distributions
## Use
[Section titled “Use”](#use)
```ts
import { Probability, poissonDistribution } from 'knotkit/distribution'
import { splitmix32 } from 'knotkit/prng'
const calls = poissonDistribution({ mean: 3 })
const atMostFive = calls.cumulativeProbability(5)
const firstCutoff = calls.quantile(atMostFive)
const percentile95 = calls.quantile(Probability.make(0.95))
const nextCount = calls.draw(splitmix32(20261119))
```
distribution.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* compute probability below a threshold in a named distribution
* find a quantile for a distribution
* draw values from an injected source according to a distribution
* summarize observed numbers with a mean, variance, quantile, histogram, or correlation
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `poissonDistribution`kind `poisson` | The quantity is a count of independent events at a known mean rate. | Probability tails use a regularized incomplete gamma function. |
| `binomialDistribution`kind `binomial` | The quantity is successes in a fixed number of independent trials with one success probability. | Probability tails use a regularized incomplete beta function. |
| `geometricDistribution`kind `geometric` | The quantity is failures before the first success in independent trials. | Mass, tails and a quantile estimate have closed forms. |
| `hypergeometricDistribution`kind `hypergeometric` | The quantity is successes in a sample drawn without replacement from a finite population. | Tail evaluation sums ratios of adjacent masses. |
| `normalDistribution`kind `normal` | The quantity is modeled as a symmetric bell-shaped real value. | Direct normal tails and inverse transform. |
| `logNormalDistribution`kind `log-normal` | The quantity is positive and its natural logarithm follows a normal distribution. | Normal tails in logarithmic coordinates. |
| `gammaDistribution`kind `gamma` | The quantity is a positive waiting time with a known gamma shape and rate. | Incomplete-gamma tails and a bracketed quantile. |
| `exponentialDistribution`kind `exponential` | The quantity is a memoryless waiting time at a known rate. | Closed-form tails and quantile. |
| `chiSquaredDistribution`kind `chi-squared` | The quantity is a sum of squared standard normals or a chi-squared test statistic. | Gamma with rate one half. |
| `betaDistribution`kind `beta` | The quantity is a continuous proportion on the unit interval with two shape parameters. | Incomplete-beta tails and a bracketed quantile. |
| `studentTDistribution`kind `student-t` | The quantity is a standardized mean of a normal sample whose variance is estimated, or a real value with heavier tails than normal. | Incomplete-beta tails and a bracketed quantile. |
| `fDistribution`kind `f` | The quantity is a ratio of two independent chi-squared variables each divided by its degrees of freedom, such as a variance ratio or ANOVA statistic. | Incomplete-beta tails and a bracketed quantile. |
| `uniformDistribution`kind `uniform` | The quantity is equally dense throughout a finite interval. | Closed-form tails and quantile. |
| `probabilityTableDistribution`kind `probability-table` | The caller has an ordered table of finite values with explicit masses. | O(n) preprocessing and O(log n) lookup and draw. |
| `customDiscreteDistribution`kind `custom-discrete` | The caller supplies a mass function over integer outcomes and a CDF for unbounded upper support. | Finite tails sum masses; inversion brackets and searches integers. |
| `customContinuousDistribution`kind `custom-continuous` | The caller supplies the density and CDF for a continuous distribution over an interval. | Uses the supplied quantile or solves the bracketed inverse. |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
* Draw 10 times from a population containing 6 successes out of 20.
* Variance with replacement: 2.10. Without replacement: 1.11.
* Without replacement, the success count is more concentrated around 3.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/demo.ts) against `knotkit/distribution`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------- |
| [`poissonDistribution`](/reference/knotkit/distribution/functions/poissondistribution/) | `PoissonDistribution` | A nonnegative finite mean defines the distribution. |
| [`binomialDistribution`](/reference/knotkit/distribution/functions/binomialdistribution/) | `BinomialDistribution` | Construct successProbability with Probability.make. |
| [`geometricDistribution`](/reference/knotkit/distribution/functions/geometricdistribution/) | `GeometricDistribution` | Construct successProbability with Probability.make. |
| [`hypergeometricDistribution`](/reference/knotkit/distribution/functions/hypergeometricdistribution/) | `HypergeometricDistribution` | Population, success count and sample size fix the distribution. |
| [`normalDistribution`](/reference/knotkit/distribution/functions/normaldistribution/) | `NormalDistribution` | Location and standard deviation define the real-valued distribution. |
| [`logNormalDistribution`](/reference/knotkit/distribution/functions/lognormaldistribution/) | `LogNormalDistribution` | Parameters describe the natural logarithm of the quantity. |
| [`gammaDistribution`](/reference/knotkit/distribution/functions/gammadistribution/) | `GammaDistribution` | Rate is the reciprocal of scale. |
| [`exponentialDistribution`](/reference/knotkit/distribution/functions/exponentialdistribution/) | `ExponentialDistribution` | Rate is the reciprocal of the mean. |
| [`chiSquaredDistribution`](/reference/knotkit/distribution/functions/chisquareddistribution/) | `ChiSquaredDistribution` | Degrees of freedom determine the shape. |
| [`betaDistribution`](/reference/knotkit/distribution/functions/betadistribution/) | `BetaDistribution` | Alpha and beta define the bounded distribution. |
| [`studentTDistribution`](/reference/knotkit/distribution/functions/studenttdistribution/) | `StudentTDistribution` | Degrees of freedom define the heavy-tailed real-valued distribution. |
| [`fDistribution`](/reference/knotkit/distribution/functions/fdistribution/) | `FDistribution` | Numerator and denominator degrees of freedom define the nonnegative ratio distribution. |
| [`uniformDistribution`](/reference/knotkit/distribution/functions/uniformdistribution/) | `UniformDistribution` | Two ordered finite bounds define the interval. |
| [`probabilityTableDistribution`](/reference/knotkit/distribution/functions/probabilitytabledistribution/) | `ProbabilityTableDistribution` | Construct the probability array with Probability.make. |
| [`customDiscreteDistribution`](/reference/knotkit/distribution/functions/customdiscretedistribution/) | `CustomDiscreteDistribution` | Evaluates a caller-provided mass function. |
| [`customContinuousDistribution`](/reference/knotkit/distribution/functions/customcontinuousdistribution/) | `CustomContinuousDistribution` | Uses an optional caller-supplied survival function and quantile. |
| [`sampleMean`](/reference/knotkit/distribution/functions/samplemean/) | `number` | Running arithmetic mean of a finite sample. |
| [`sampleVariance`](/reference/knotkit/distribution/functions/samplevariance/) | `number` | Welford variance; degreesOfFreedomCorrection defaults to 1. |
| [`median`](/reference/knotkit/distribution/functions/median/) | `number` | Exact median of a sorted copy. |
| [`sampleQuantile`](/reference/knotkit/distribution/functions/samplequantile/) | `number` | Type 7 linear-interpolation quantile of a sorted copy. |
| [`histogram`](/reference/knotkit/distribution/functions/histogram/) | `Histogram` | Counts per half-open bin, last bin closed, as np.histogram. |
| [`covariance`](/reference/knotkit/distribution/functions/covariance/) | `number` | Welford co-moment covariance; degreesOfFreedomCorrection defaults to 1. |
| [`pearsonCorrelation`](/reference/knotkit/distribution/functions/pearsoncorrelation/) | `number` | Product-moment correlation clamped to \[-1, 1]. |
Cost per member. Open a row for every operation.
`sampleMean` 1 members
| Member | Cost |
| --------- | --------- |
| `compare` | O(n) time |
`sampleVariance` 1 members
| Member | Cost |
| --------- | --------- |
| `compare` | O(n) time |
`median` 1 members
| Member | Cost |
| --------- | ------------------------------------ |
| `compare` | O(n log n) time and O(n) extra space |
`sampleQuantile` 1 members
| Member | Cost |
| --------- | ------------------------------------ |
| `compare` | O(n log n) time and O(n) extra space |
`histogram` 1 members
| Member | Cost |
| --------- | ------------------------- |
| `compare` | O(n log n + n log k) time |
`covariance` 1 members
| Member | Cost |
| --------- | --------- |
| `compare` | O(n) time |
`pearsonCorrelation` 1 members
| Member | Cost |
| --------- | --------- |
| `compare` | O(n) time |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ---------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------- |
| randomness per draw | `RandomSource` | [`knotkit/prng`](/modules/prng/) |
| probability callbacks for custom distributions | `CustomDiscreteDistributionParameters or CustomContinuousDistributionParameters` | `caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `DistributionInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `DistributionInvalidInputError`
`INVALID_PARAMETER` `INVALID_PROBABILITY` `INVALID_TABLE` `INVALID_SAMPLE` `ZERO_VARIANCE`
* `Other`
`INVALID_ARGUMENT` `INVALID_MOMENT_ORDER` `INVALID_CALLBACK_VALUE` `QUANTILE_NOT_BRACKETED`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------- | ------------------------------------------------------ |
| shuffle or sample from an array | [`knotkit/sampling`](/modules/sampling/) |
| fit a distribution's parameters to data | SciPy or R |
| test whether draws fit a distribution | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |
| evaluate a multivariate distribution | SciPy or R |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/distribution/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/distribution/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/distributionCopy prompt
```
Use knotkit/distribution for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/distribution'.
Exports:
- `poissonDistribution` → `PoissonDistribution`: A nonnegative finite mean defines the distribution.
- `binomialDistribution` → `BinomialDistribution`: Construct successProbability with Probability.make.
- `geometricDistribution` → `GeometricDistribution`: Construct successProbability with Probability.make.
- `hypergeometricDistribution` → `HypergeometricDistribution`: Population, success count and sample size fix the distribution.
- `normalDistribution` → `NormalDistribution`: Location and standard deviation define the real-valued distribution.
- `logNormalDistribution` → `LogNormalDistribution`: Parameters describe the natural logarithm of the quantity.
- `gammaDistribution` → `GammaDistribution`: Rate is the reciprocal of scale.
- `exponentialDistribution` → `ExponentialDistribution`: Rate is the reciprocal of the mean.
- `chiSquaredDistribution` → `ChiSquaredDistribution`: Degrees of freedom determine the shape.
- `betaDistribution` → `BetaDistribution`: Alpha and beta define the bounded distribution.
- `studentTDistribution` → `StudentTDistribution`: Degrees of freedom define the heavy-tailed real-valued distribution.
- `fDistribution` → `FDistribution`: Numerator and denominator degrees of freedom define the nonnegative ratio distribution.
- `uniformDistribution` → `UniformDistribution`: Two ordered finite bounds define the interval.
- `probabilityTableDistribution` → `ProbabilityTableDistribution`: Construct the probability array with Probability.make.
- `customDiscreteDistribution` → `CustomDiscreteDistribution`: Evaluates a caller-provided mass function.
- `customContinuousDistribution` → `CustomContinuousDistribution`: Uses an optional caller-supplied survival function and quantile.
- `sampleMean` → `number`: Running arithmetic mean of a finite sample.
- `sampleVariance` → `number`: Welford variance; degreesOfFreedomCorrection defaults to 1.
- `median` → `number`: Exact median of a sorted copy.
- `sampleQuantile` → `number`: Type 7 linear-interpolation quantile of a sorted copy.
- `histogram` → `Histogram`: Counts per half-open bin, last bin closed, as np.histogram.
- `covariance` → `number`: Welford co-moment covariance; degreesOfFreedomCorrection defaults to 1.
- `pearsonCorrelation` → `number`: Product-moment correlation clamped to [-1, 1].
Pick the layout by these rules:
- `poissonDistribution` (kind 'poisson') when The quantity is a count of independent events at a known mean rate.
- `binomialDistribution` (kind 'binomial') when The quantity is successes in a fixed number of independent trials with one success probability.
- `geometricDistribution` (kind 'geometric') when The quantity is failures before the first success in independent trials.
- `hypergeometricDistribution` (kind 'hypergeometric') when The quantity is successes in a sample drawn without replacement from a finite population.
- `normalDistribution` (kind 'normal') when The quantity is modeled as a symmetric bell-shaped real value.
- `logNormalDistribution` (kind 'log-normal') when The quantity is positive and its natural logarithm follows a normal distribution.
- `gammaDistribution` (kind 'gamma') when The quantity is a positive waiting time with a known gamma shape and rate.
- `exponentialDistribution` (kind 'exponential') when The quantity is a memoryless waiting time at a known rate.
- `chiSquaredDistribution` (kind 'chi-squared') when The quantity is a sum of squared standard normals or a chi-squared test statistic.
- `betaDistribution` (kind 'beta') when The quantity is a continuous proportion on the unit interval with two shape parameters.
- `studentTDistribution` (kind 'student-t') when The quantity is a standardized mean of a normal sample whose variance is estimated, or a real value with heavier tails than normal.
- `fDistribution` (kind 'f') when The quantity is a ratio of two independent chi-squared variables each divided by its degrees of freedom, such as a variance ratio or ANOVA statistic.
- `uniformDistribution` (kind 'uniform') when The quantity is equally dense throughout a finite interval.
- `probabilityTableDistribution` (kind 'probability-table') when The caller has an ordered table of finite values with explicit masses.
- `customDiscreteDistribution` (kind 'custom-discrete') when The caller supplies a mass function over integer outcomes and a CDF for unbounded upper support.
- `customContinuousDistribution` (kind 'custom-continuous') when The caller supplies the density and CDF for a continuous distribution over an interval.
Inputs and their sources:
- randomness per draw: `RandomSource` from `knotkit/prng`
- probability callbacks for custom distributions: `CustomDiscreteDistributionParameters or CustomContinuousDistributionParameters` from `caller`
Use something else when:
- shuffle or sample from an array → knotkit/sampling
- fit a distribution's parameters to data → SciPy or R
- test whether draws fit a distribution → knotkit/hypothesis-test
- evaluate a multivariate distribution → SciPy or R
Errors are DistributionInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/distribution.md
Types: node_modules/knotkit/distribution/ and https://knotkit.jkomyno.dev/reference/knotkit/distribution/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/distribution/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/distribution/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/distribution/knotkit.capability.json)suggest a change to the source record
# knotkit/e-graph
> Propagates equalities through expressions and extracts a minimum-cost equivalent expression
## Use
[Section titled “Use”](#use)
```ts
import { eGraph } from 'knotkit/e-graph'
const graph = eGraph()
const x = graph.add('x')
const plusZero = graph.add('+', [x, graph.add('0')])
const left = graph.add('sin', [x])
const right = graph.add('sin', [plusZero])
graph.equivalent(left, right) // false
graph.unite(x, plusZero) // the caller supplies x = x + 0
graph.equivalent(left, right) // true, by congruence
```
e-graph.ts●
ResetEditRun
```
```
```ts
const product = graph.add('×', [graph.add('2'), x])
const sum = graph.add('+', [x, x])
graph.unite(product, sum)
// A printer counts occurrences of x.
graph.extract(product, (op) => Number(op === 'x')).operator // '×'
// A code generator charges five units for multiplication and one for every other operator.
graph.extract(product, (op) => (op === '×' ? 5 : 1)).operator // '+'
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* share repeated subexpressions even when their operands were built from different equivalent terms
* recognize that replacing an operand with an equal operand preserves an expression
* select the cheapest equivalent expression under a caller's operator prices
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `eGraph`kind `hash-consed` | the caller supplies term equalities and needs an immediate equivalence query or a minimum-cost finite expression | an effective merge rescans stored terms until the congruence relation stabilizes |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
* Declaring x + 0 equal to x also equates all 6 nested sin pairs.
* Multiplication price 1 selects × (cost 3). Price 6 selects + (cost 5).
* Prices count each occurrence. Here x costs 2, addition costs 1, and literals cost 0.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/demo.ts) against `knotkit/e-graph`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| -------------------------------------------------------- | ------------ | --------------------------------------------------------------------- |
| [`eGraph`](/reference/knotkit/e-graph/functions/egraph/) | `EGraph` | Interns ordered terms and eagerly closes each merge under congruence. |
Cost per member. Open a row for every operation.
`eGraph` 5 members
| Member | Cost |
| ------------ | ---------------------------------------------------------------------- |
| `size` | O(1) |
| `add` | O(k \* alpha(n)) amortized for k children |
| `unite` | O(n \* (n + m) \* alpha(n)) per effective merge, O(alpha(n)) otherwise |
| `equivalent` | O(alpha(n)) amortized |
| `extract` | O((n + m) \* alpha(n) + n log(n + 1)), excluding the price callback |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ----------------------------------- | -------------------------- | ------------ |
| local price per operator occurrence | `(operator: Op) => number` | `the caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `EGraphInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `FOREIGN_CLASS` `INVALID_COST` `COST_OVERFLOW`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------------- | ------------------------------------------------ |
| merge groups of opaque values | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| discover substitutions by pattern matching and repeatedly applying rewrite rules | egglog |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/e-graph/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/e-graph/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/e-graphCopy prompt
```
Use knotkit/e-graph for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/e-graph'.
Exports:
- `eGraph` → `EGraph`: Interns ordered terms and eagerly closes each merge under congruence.
Pick the layout by these rules:
- `eGraph` (kind 'hash-consed') when the caller supplies term equalities and needs an immediate equivalence query or a minimum-cost finite expression
Inputs and their sources:
- local price per operator occurrence: `(operator: Op) => number` from `the caller`
Use something else when:
- merge groups of opaque values → knotkit/disjoint-set
- discover substitutions by pattern matching and repeatedly applying rewrite rules → egglog
Errors are EGraphInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/e-graph.md
Types: node_modules/knotkit/e-graph/ and https://knotkit.jkomyno.dev/reference/knotkit/e-graph/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/e-graph/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/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/e-graph/knotkit.capability.json)suggest a change to the source record
# knotkit/errors
> Provides the base error classes every Knotkit package throws from, discriminated by package, category, and cause
## Use
[Section titled “Use”](#use)
```ts
import { isKnotkitError, isParseError } from 'knotkit/errors'
import { deserializeSnapshotSet } from 'knotkit/snapshot-set/wire'
import { stringCodec } from 'knotkit/wire'
const payload = new Uint8Array() // Empty payload triggers a parse error.
try {
deserializeSnapshotSet(payload, { codec: stringCodec })
} catch (error) {
if (isParseError(error)) {
console.error('rejected payload:', error.moduleName, error.code)
} else if (isKnotkitError(error)) {
console.error(error.moduleName, error._tag, error.code, error.message)
} else {
throw error
}
}
```
errors.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* catch a failure from any Knotkit package without importing each package's own error classes
* read which package failed, which category, and the exact code from a caught error
* recognize a Knotkit error that crossed a realm or came from a duplicate copy of a package, where instanceof reports a false negative
* format an unknown thrown value into a message without a hostile toString replacing the caller's error
* fail a decode on the first invalid element using the throwing package's own error class and code
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
| [`safeString`](/reference/knotkit/errors/functions/safestring/) | `string` | Format an unknown value for a message without letting a hostile toString or Symbol.toPrimitive replace the caller's error. |
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| throw or catch errors in an application that depends on no Knotkit package | the platform Error class or a project-local subclass with its own codes |
| throw a concrete error from your own Knotkit package | extend InvalidInputError or ParseError with a package-scoped subclass and a closed code list |
| carry an error's package name, category, and code across a process or JSON boundary | an explicit error envelope marshalled by the caller, because no class here serializes |
| validate caller input or decode a payload for a structure that is not a Knotkit package | a schema validator such as Zod, or a project-local error class |
## Performance
[Section titled “Performance”](#performance)
This module has no benchmark suite. The costs above are its performance contract.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/errorsCopy prompt
```
Use knotkit/errors for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/errors'.
Exports:
- `safeString` → `string`: Format an unknown value for a message without letting a hostile toString or Symbol.toPrimitive replace the caller's error.
Use something else when:
- throw or catch errors in an application that depends on no Knotkit package → the platform Error class or a project-local subclass with its own codes
- throw a concrete error from your own Knotkit package → extend InvalidInputError or ParseError with a package-scoped subclass and a closed code list
- carry an error's package name, category, and code across a process or JSON boundary → an explicit error envelope marshalled by the caller, because no class here serializes
- validate caller input or decode a payload for a structure that is not a Knotkit package → a schema validator such as Zod, or a project-local error class
Full page: https://knotkit.jkomyno.dev/modules/errors.md
Types: node_modules/knotkit/errors/ and https://knotkit.jkomyno.dev/reference/knotkit/errors/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/errors/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/errors/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/errors/knotkit.capability.json)suggest a change to the source record
# knotkit/evolution
> Runs deterministic population evolution with index-based parent selection and immutable permutation operators
## Use
[Section titled “Use”](#use)
```ts
import { evolution, inversionMutation } from 'knotkit/evolution'
import { splitmix32 } from 'knotkit/prng'
const engine = evolution({
initialPopulation: [
[0, 1, 2, 3],
[0, 2, 1, 3],
[3, 1, 2, 0],
],
evaluate: (candidate) => candidate.reduce((total, value, index) => total + Math.abs(value - index), 0),
objective: 'minimize',
random: splitmix32(42),
nextPopulation: ({ snapshot }) => snapshot.population.map(({ value }) => inversionMutation(value, 1, 2)),
})
engine.run(20)
engine.snapshot().best // { value, score }
```
evolution.ts●
ResetEditRun
```
```
```ts
import { type EvolutionContext, inversionMutation, rankSelection } from 'knotkit/evolution'
const nextPopulation = ({ snapshot, random }: EvolutionContext) => {
const scores = snapshot.population.map(({ score }) => score)
const selected = rankSelection(random, scores, scores.length, 'minimize')
return selected.map((index) => inversionMutation(snapshot.population[index].value, 1, 2))
}
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* find a good route or schedule where improving one position at a time gets stuck
* keep the best candidate seen across generations while a whole population changes
* select parents in proportion to rank, then recombine two orderings into one child ordering
* run an optimizer deterministically from a seed so a recorded run replays exactly
* decide when to stop from a stagnation count instead of a fixed generation budget
* mutate or cross a permutation without touching the array the caller handed in
## Worked example
[Section titled “Worked example”](#worked-example)
* Evolve 12 permutations of 8 items for 30 generations, using seeds 17 and 42.
* Best displacement went from 10 to 0. Best order: \[0, 1, 2, 3, 4, 5, 6, 7].
* The population score can rise while the engine retains the best candidate it has seen.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/evolution/demo.ts) against `knotkit/evolution`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`evolution`](/reference/knotkit/evolution/functions/evolution/) | `Evolution` | Generation-at-a-time engine: construction evaluates the initial population once, each \`step\` calls the caller's policy and evaluates its output once, and no intermediate generation is retained. |
| [`tournamentSelection`](/reference/knotkit/evolution/functions/tournamentselection/) | `readonly number[]` | \`selectionSize\` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t. |
| [`exponentialRankWeights`](/reference/knotkit/evolution/functions/exponentialrankweights/) | `readonly number[]` | \`Math.exp(-rank)\` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n). |
| [`exponentialRankLogWeights`](/reference/knotkit/evolution/functions/exponentialranklogweights/) | `readonly number[]` | \`-rank\` from that same ranking pass, finite for every entry so it feeds \`weightedSampleFromLogWeights\` without an exponentiation that underflows; O(n log n). |
| [`rankSelection`](/reference/knotkit/evolution/functions/rankselection/) | `readonly number[]` | \`exponentialRankWeights\` consumed once per output through \`weightedChoice\`, selecting with replacement; O(n log n + k n). |
| [`orderCrossover`](/reference/knotkit/evolution/functions/ordercrossover/) | `readonly T[]` | One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a \`Set\` and a donor cycle. |
| [`swapMutation`](/reference/knotkit/evolution/functions/swapmutation/) | `readonly T[]` | Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n). |
| [`inversionMutation`](/reference/knotkit/evolution/functions/inversionmutation/) | `readonly T[]` | Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n). |
| [`rotateLeftMutation`](/reference/knotkit/evolution/functions/rotateleftmutation/) | `readonly T[]` | Rotate the inclusive segment one position left in a copy; requires \`first <= second\`. O(n). |
| [`rotateRightMutation`](/reference/knotkit/evolution/functions/rotaterightmutation/) | `readonly T[]` | Rotate the inclusive segment one position right in a copy; requires \`first <= second\`. O(n). |
Cost per member. Open a row for every operation.
`evolution` 3 members
| Member | Cost |
| ---------- | ----------------------------------- |
| `snapshot` | O(1) |
| `step` | O(n) plus evaluator and policy work |
| `run` | O(generations) steps |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| --------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------ |
| randomness, drawn only by the caller's policy through the context and never allocated by the engine | `RandomSource` | [`knotkit/prng`](/modules/prng/) |
| fitness, which decides every score and therefore every selection outcome | `(candidate: T) => number` | `the caller` |
| the next-generation policy, which owns selection, crossover, and mutation | `(context: EvolutionContext) => readonly T[]` | `the caller` |
| objective direction, which decides what a score better than another means | `Objective` | [`knotkit/evolution`](/modules/evolution/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `EvolutionInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `EvolutionInvalidInputError`
`EMPTY_POPULATION` `INVALID_SCORE` `INVALID_SELECTION_SIZE` `INVALID_TOURNAMENT_SIZE` `INVALID_OBJECTIVE` `INVALID_PERMUTATION` `INVALID_INDEX` `INVALID_CUT` `DUPLICATE_ELEMENT` `UNEQUAL_PARENT_DOMAIN`
* `Other`
`INVALID_GENERATION_COUNT`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| a seeded random source, or control over the draw sequence | [`knotkit/prng`](/modules/prng/) |
| draw a sample, a pair, or a weighted selection outside a population | [`knotkit/sampling`](/modules/sampling/) |
| a stopping rule, a checkpoint schedule, or a per-generation trace | caller code around bounded \`run\` calls; the engine retains only the current generation |
| optimize real-valued parameters where a gradient exists | a derivative-based optimizer, since the shipped operators act on permutations |
| order the population by score | Array.prototype.sort over \`snapshot().population\` |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/evolution/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/evolution/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/evolutionCopy prompt
```
Use knotkit/evolution for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/evolution'.
Exports:
- `evolution` → `Evolution`: Generation-at-a-time engine: construction evaluates the initial population once, each `step` calls the caller's policy and evaluates its output once, and no intermediate generation is retained.
- `tournamentSelection` → `readonly number[]`: `selectionSize` winners, each from a tournament of distinct indices sampled by Floyd's algorithm; the same winner may repeat across tournaments and ties keep the first sampled index. O(k(n + t log t)) with tournament size t.
- `exponentialRankWeights` → `readonly number[]`: `Math.exp(-rank)` per score after one ranking pass from best to worst, equal scores sharing a competition rank; O(n log n).
- `exponentialRankLogWeights` → `readonly number[]`: `-rank` from that same ranking pass, finite for every entry so it feeds `weightedSampleFromLogWeights` without an exponentiation that underflows; O(n log n).
- `rankSelection` → `readonly number[]`: `exponentialRankWeights` consumed once per output through `weightedChoice`, selecting with replacement; O(n log n + k n).
- `orderCrossover` → `readonly T[]`: One child that keeps the inclusive cut segment of the first parent and fills the remaining positions in the second parent's cyclic order; O(n) expected, allocating a `Set` and a donor cycle.
- `swapMutation` → `readonly T[]`: Swap two positions in a copy; either index order is accepted and equal indices are a valid no-op. O(n).
- `inversionMutation` → `readonly T[]`: Reverse the inclusive segment between two positions in a copy; either index order is accepted. O(n).
- `rotateLeftMutation` → `readonly T[]`: Rotate the inclusive segment one position left in a copy; requires `first <= second`. O(n).
- `rotateRightMutation` → `readonly T[]`: Rotate the inclusive segment one position right in a copy; requires `first <= second`. O(n).
Inputs and their sources:
- randomness, drawn only by the caller's policy through the context and never allocated by the engine: `RandomSource` from `knotkit/prng`
- fitness, which decides every score and therefore every selection outcome: `(candidate: T) => number` from `the caller`
- the next-generation policy, which owns selection, crossover, and mutation: `(context: EvolutionContext) => readonly T[]` from `the caller`
- objective direction, which decides what a score better than another means: `Objective` from `knotkit/evolution`
Use something else when:
- a seeded random source, or control over the draw sequence → knotkit/prng
- draw a sample, a pair, or a weighted selection outside a population → knotkit/sampling
- a stopping rule, a checkpoint schedule, or a per-generation trace → caller code around bounded `run` calls; the engine retains only the current generation
- optimize real-valued parameters where a gradient exists → a derivative-based optimizer, since the shipped operators act on permutations
- order the population by score → Array.prototype.sort over `snapshot().population`
Errors are EvolutionInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/evolution.md
Types: node_modules/knotkit/evolution/ and https://knotkit.jkomyno.dev/reference/knotkit/evolution/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/evolution/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/evolution/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/evolution/knotkit.capability.json)suggest a change to the source record
# knotkit/frequency-table
> Maintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain
## Use
[Section titled “Use”](#use)
```ts
import { fenwickFrequencyTable } from 'knotkit/frequency-table'
const counts = fenwickFrequencyTable(10)
counts.add(2, 2)
counts.add(7)
counts.add(9)
counts.count(2) // 2
// Sorted observations are [2, 2, 7, 9].
counts.at(Math.floor((counts.size - 1) / 2)) // 2, the lower median
counts.rangeSum(2, 8) // 3
counts.add(2, -1)
counts.at(-1) // 9, the largest observed key
```
frequency-table.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* read the exact number of occurrences of a key
* track repeated integer observations as items enter and leave
* sum frequencies between two bounds after updates
* read a median or quantile by its position among all observations
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `fenwickFrequencyTable`kind `fenwick` | prefix sums or rank selections repeatedly span many keys between updates | four bytes per addressable key and one sentinel counter, with at most 2^32 - 1 occurrences |
| `flatFrequencyTable`kind `flat` | the domain has few keys or the workload primarily updates and reads individual counts | four bytes per addressable key; selection scans from zero to the selected key |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
Largest table8,19213Reset
* fenwick: prefixSum(8191) = 5, count(0) = 3.
* flat: prefixSum(8191) = 5, count(0) = 3.
* The flat layout scans the prefix. Fenwick sums one partial counter per set bit in the prefix length.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/demo.ts) against `knotkit/frequency-table` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ---------------------------------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------- |
| [`fenwickFrequencyTable`](/reference/knotkit/frequency-table/functions/fenwickfrequencytable/) | `FrequencyTable` | Binary indexed tree of exact nonnegative integer frequencies. |
| [`flatFrequencyTable`](/reference/knotkit/frequency-table/functions/flatfrequencytable/) | `FrequencyTable` | One unsigned counter per key. Range sums and rank selection scan counters. |
Cost per member. Open a row for every operation.
`fenwickFrequencyTable` 7 members
| Member | Cost |
| ----------- | -------- |
| `add` | O(log C) |
| `prefixSum` | O(log C) |
| `rangeSum` | O(log C) |
| `at` | O(log C) |
| `clear` | O(C) |
| `size` | O(1) |
| `count` | O(log C) |
`flatFrequencyTable` 7 members
| Member | Cost |
| ----------- | ------------------ |
| `add` | O(1) |
| `prefixSum` | O(end + 1) |
| `rangeSum` | O(end - start + 1) |
| `at` | O(C) |
| `clear` | O(C) |
| `size` | O(1) |
| `count` | O(1) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `FrequencyTableInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_CAPACITY` `INVALID_INDEX` `INVALID_RANGE` `INVALID_DELTA` `COUNT_UNDERFLOW` `COUNT_OVERFLOW`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------ | -------------------------------------------------- |
| rank keys under a custom comparator or store payloads | [`knotkit/ordered-map`](/modules/ordered-map/) |
| membership and set algebra on unique unsigned IDs | [`knotkit/bitset`](/modules/bitset/) |
| prefix sums over immutable signed values | a prefix-sum array |
| estimate per-key frequencies in a stream with bounded memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/frequency-table/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/frequency-table/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#frequency-table).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/frequency-tableCopy prompt
```
Use knotkit/frequency-table for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/frequency-table'.
Exports:
- `fenwickFrequencyTable` → `FrequencyTable`: Binary indexed tree of exact nonnegative integer frequencies.
- `flatFrequencyTable` → `FrequencyTable`: One unsigned counter per key. Range sums and rank selection scan counters.
Pick the layout by these rules:
- `fenwickFrequencyTable` (kind 'fenwick') when prefix sums or rank selections repeatedly span many keys between updates
- `flatFrequencyTable` (kind 'flat') when the domain has few keys or the workload primarily updates and reads individual counts
Use something else when:
- rank keys under a custom comparator or store payloads → knotkit/ordered-map
- membership and set algebra on unique unsigned IDs → knotkit/bitset
- prefix sums over immutable signed values → a prefix-sum array
- estimate per-key frequencies in a stream with bounded memory → knotkit/scalar-sketch
Errors are FrequencyTableInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/frequency-table.md
Types: node_modules/knotkit/frequency-table/ and https://knotkit.jkomyno.dev/reference/knotkit/frequency-table/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/frequency-table/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/frequency-table/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/frequency-table/knotkit.capability.json)suggest a change to the source record
# knotkit/graph
> Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
## Use
[Section titled “Use”](#use)
```ts
import { compressedSparseRowGraph, topologicalOrder } from 'knotkit/graph'
// [course, prerequisite] pairs: each edge runs prerequisite -> course.
const prerequisites = [
[1, 0],
[2, 0],
[3, 1],
[3, 2],
] as const
const courses = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: prerequisites.map(([course, before]) => [before, course] as const),
})
const result = topologicalOrder(courses)
if (result.acyclic) result.order // Int32Array [0, 1, 2, 3]
else result.cycle // the courses that wait on each other
```
graph.ts●
ResetEditRun
```
```
```ts
import { compressedSparseRowGraph, dijkstra, path } from 'knotkit/graph'
const times = [
[2, 1, 1],
[2, 3, 1],
[3, 4, 1],
] as const
const network = compressedSparseRowGraph({ vertexCount: 5, directed: true, weighted: true, edges: times })
const delays = dijkstra(network, { sources: [2] })
delays.distance // Float64Array [Infinity, 1, 0, 1, 2]
path(delays, 4) // Int32Array [2, 3, 4]
```
```ts
import { breadthFirstSearch, connectedComponents, gridAdjacency } from 'knotkit/graph'
const grid = [
[2, 1, 1],
[1, 1, 0],
[0, 1, 1],
]
const board = gridAdjacency({ rows: 3, columns: 3, open: (cell) => grid[Math.floor(cell / 3)][cell % 3] !== 0 })
const { distance } = breadthFirstSearch(board, { sources: [board.cell(0, 0)] })
Math.max(...distance) // 4 minutes until the last orange rots
// A closed cell is still a vertex, alone in its own component, so count patches among the open cells.
const { component } = connectedComponents(board)
const patches = new Set()
for (let cell = 0; cell < board.vertexCount; cell += 1)
if (grid[Math.floor(cell / 3)][cell % 3] !== 0) patches.add(component[cell])
patches.size // 1 patch of oranges; connectedComponents(board).count is 3, counting each empty cell
```
```ts
import { adjacencyListGraph } from 'knotkit/graph'
const roads = adjacencyListGraph({ vertexCount: 2, directed: false, weighted: true })
const town = roads.addVertex() // 2
roads.addEdge(0, town, 7) // true
roads.addEdge(town, 0, 7) // false: the same road, already stored
roads.deleteEdge(0, town) // true
```
```ts
import { breadthFirstSearch, type Adjacency } from 'knotkit/graph'
const words = ['hot', 'dot', 'dog', 'cog', 'lot', 'log']
const oneLetterApart = (a: string, b: string) => [...a].filter((letter, index) => letter !== b[index]).length === 1
const ladder: Adjacency = {
vertexCount: words.length,
directed: false,
forEachNeighbor: (word, visit) => {
for (let other = 0; other < words.length; other += 1) if (oneLetterApart(words[word], words[other])) visit(other, 1)
},
}
breadthFirstSearch(ladder, { sources: [0] }).distance[3] // 3 steps from "hot" to "cog"
```
```ts
import { __GRAPH_LAYOUTS } from 'knotkit/graph'
const { directed, weighted, parallelEdges, selfLoops } = mutable
const frozen = __GRAPH_LAYOUTS['compressed-sparse-row']({
vertexCount: mutable.vertexCount,
directed,
weighted,
parallelEdges,
selfLoops,
edges: mutable.edges(),
})
```
```ts
const ids = new Map()
const id = (key: string) => ids.get(key) ?? (ids.set(key, ids.size), ids.size - 1)
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* find the fewest-hops route between two points or the cheapest routes to selected destinations, all reachable points, or between every pair on a small graph
* order tasks, builds, or courses so every dependency comes first, or find the cycle that makes that impossible
* count the islands or connected pieces of a map, a grid, or a network, and say which piece each item is in
* decide whether one item can reach another, and list the steps of the path between them
* ask who depends on an item and what it depends on, with in-degree and out-degree
* store a graph from an edge list as compact typed arrays, and persist it as bytes
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `compressedSparseRowGraph`kind `compressed-sparse-row` | the edge set is known when you build the graph, whatever its density | 4(n + 1) + 4m' bytes, plus 8m' weighted, where m' is the stored arcs (about 2m undirected), plus 4n bytes once inDegree is asked on a directed graph; breadth-first search measured within 1.2 times of a hand-written CSR loop over the same rows at 100,000 vertices of degree 10 |
| `adjacencyListGraph`kind `adjacency-list` | edges or vertices arrive after the graph is built | 12n + 4m' bytes built from edges, plus 8m' weighted, doubled for reverse rows when directed, and up to about twice that after edits until a compaction; 4.6 bytes per stored arc undirected and 5.2 directed at degree 10, against 4.2 and 4.4 for compressed-sparse-row; addEdge is O(log d + d) amortized, and breadth-first search measured within 1.3 times of compressed-sparse-row, and within 1.11 times from degree 10 up |
| `adjacencyMatrixGraph`kind `adjacency-matrix` | no vertex pair repeats an edge, at least 5% of vertex pairs are edges, you probe hasEdge, and n² / 8 bytes (8n² weighted) fit in 256 MiB | n² / 8 bytes unweighted and 8n² weighted whatever the edge count; hasEdge measured 2.8 to 3.2 times faster than the other layouts at 25% density, and searches 4 to 11 times slower because every walk scans the absent pairs |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/graph/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
Vertices2,04811Reset
* Dijkstra finds distance 10 / 10 / 10 across packed rows, list, and matrix on the same weighted edges.
* The storage model counts buffers for fresh, unweighted layouts over 2,048 vertices.
* Implicit grid BFS finds 22 reachable cells without storing edges.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/graph/demo.ts) against `knotkit/graph` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`compressedSparseRowGraph`](/reference/knotkit/graph/functions/compressedsparserowgraph/) | `CompressedSparseRowGraph` | Immutable graph packed as an Int32Array of row offsets and one flat Int32Array of neighbors, plus a flat Float64Array of weights when weighted; a directed graph counts its in-degrees on the first inDegree call and builds its transposed rows on the first forEachPredecessor call. |
| [`adjacencyListGraph`](/reference/knotkit/graph/functions/adjacencylistgraph/) | `MutableGraph` | Mutable graph with one sorted row per vertex, each a slot with spare capacity in one shared Int32Array that compacts once edits leave enough dead space, and a reverse row per vertex when directed; the only layout with addVertex, addEdge, and deleteEdge. |
| [`adjacencyMatrixGraph`](/reference/knotkit/graph/functions/adjacencymatrixgraph/) | `AdjacencyMatrixGraph` | Immutable dense graph with one bit per vertex pair when unweighted or one Float64Array cell per pair when weighted, checked against GRAPH_MAX_MATRIX_BYTES before allocation; it cannot hold parallel edges. |
| [`breadthFirstSearch`](/reference/knotkit/graph/functions/breadthfirstsearch/) | `BreadthFirstSearchResult` | Fewest-hops distance, parent, and visit order from one or more sources over any Adjacency, optionally stopping at a target; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because every reached row's walk costs its degree on compressed-sparse-row and adjacency-list, but O(n / 32 + d) on an unweighted adjacency-matrix and O(n) on a weighted one. |
| [`dijkstra`](/reference/knotkit/graph/functions/dijkstra/) | `DijkstraResult` | Least total cost and parent from one or more sources over any Adjacency. Stops once all requested destinations settle, or searches all reachable vertices. Supports a per-edge cost override and checks non-negative costs on every edge walked. Uses knotkit/heap's indexed priority queue, with O((n + m) log n) time on compressed-sparse-row and adjacency-list, plus O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one for the row walks. |
| [`topologicalOrder`](/reference/knotkit/graph/functions/topologicalorder/) | `TopologicalOrderResult` | Kahn's algorithm over a directed Adjacency, returning an order or one directed cycle as a result rather than a throw; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because it walks every row. |
| [`connectedComponents`](/reference/knotkit/graph/functions/connectedcomponents/) | `ConnectedComponentsResult` | Component count and a label per vertex for an undirected Adjacency, labels numbered by each component's smallest vertex, every isolated or closed grid cell a component of its own; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one. |
| [`floydWarshall`](/reference/knotkit/graph/functions/floydwarshall/) | `FloydWarshallResult` | Every pairwise shortest distance as a row-major n × n Float64Array, or a vertex on a negative cycle; runs on every layout and allocates its own 8n²-byte matrix, so it does not decide the storage; O(n³) time plus one walk of every row, and a Bellman-Ford pass over the rows when a cycle is negative. |
| [`path`](/reference/knotkit/graph/functions/path/) | `Int32Array \| undefined` | The vertices from a source to a target, read back from a breadthFirstSearch or dijkstra result; O(path length). |
| [`gridAdjacency`](/reference/knotkit/graph/functions/gridadjacency/) | `GridAdjacency` | An Adjacency over a rows × columns board with 4 or 8 moves per cell, closed cells, and refused moves, computed on demand rather than stored. |
Cost per member. Open a row for every operation.
`compressedSparseRowGraph` 8 members
| Member | Cost |
| -------------------- | ------------------------------------------------------------ |
| `build` | O(n + m) |
| `hasEdge` | O(log d) |
| `outDegree` | O(1) |
| `inDegree` | O(1) after a lazy O(n + m) count into 4n bytes when directed |
| `forEachNeighbor` | O(d) |
| `forEachPredecessor` | O(d) after a lazy O(n + m) transpose when directed |
| `neighbors` | O(d) |
| `edges` | O(n + m) |
`adjacencyListGraph` 11 members
| Member | Cost |
| -------------------- | ---------------------- |
| `build` | O(n + m) |
| `hasEdge` | O(log d) |
| `outDegree` | O(1) |
| `inDegree` | O(1) |
| `forEachNeighbor` | O(d) |
| `forEachPredecessor` | O(d) |
| `neighbors` | O(d) |
| `edges` | O(n + m) |
| `addVertex` | O(1) amortized |
| `addEdge` | O(log d + d) amortized |
| `deleteEdge` | O(log d + d) amortized |
`adjacencyMatrixGraph` 8 members
| Member | Cost |
| -------------------- | ------------------------------ |
| `build` | O(n² / 32 + m), O(n²) weighted |
| `hasEdge` | O(1) |
| `outDegree` | O(1) |
| `inDegree` | O(1) |
| `forEachNeighbor` | O(n / 32 + d), O(n) weighted |
| `forEachPredecessor` | O(n) when directed |
| `neighbors` | O(n / 32 + d), O(n) weighted |
| `edges` | O(n² / 32 + m) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `GraphInvalidInputError` or `GraphParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `GraphInvalidInputError`
`INVALID_VERTEX_COUNT` `INVALID_VERTEX` `INVALID_EDGE` `INVALID_WEIGHT` `MISSING_WEIGHT` `UNEXPECTED_WEIGHT` `INVALID_FLAG` `SELF_LOOP` `PARALLEL_EDGE` `PARALLEL_EDGES_UNSUPPORTED` `NEGATIVE_WEIGHT` `DIRECTED_GRAPH_REQUIRED` `UNDIRECTED_GRAPH_REQUIRED` `INVALID_GRID` `MAX_CAPACITY_EXCEEDED` `MODIFIED_DURING_ITERATION`
* `GraphParseError`
`FOREIGN_GRAPH` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `INVALID_EDGE_SEQUENCE` `INVALID_GRAPH_FLAGS` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/graph/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeGraph`, `deserializeGraph`
* Formats
binary
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| merge groups and ask whether two items are connected, without keeping the edges | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| a visited flag per vertex you already index by number | a pre-sized Uint8Array |
| a graph keyed by strings with attributes on every node and edge, or a format such as GraphML | graphology |
| maximum flow, matching, minimum spanning trees, or strongly connected components | Effect's Graph module, until a caller moves one of them here |
| an ordered frontier of your own, such as A\* with a heuristic | [`knotkit/heap`](/modules/heap/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/graph/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/graph/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#graph).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/graphCopy prompt
```
Use knotkit/graph for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/graph'.
Exports:
- `compressedSparseRowGraph` → `CompressedSparseRowGraph`: Immutable graph packed as an Int32Array of row offsets and one flat Int32Array of neighbors, plus a flat Float64Array of weights when weighted; a directed graph counts its in-degrees on the first inDegree call and builds its transposed rows on the first forEachPredecessor call.
- `adjacencyListGraph` → `MutableGraph`: Mutable graph with one sorted row per vertex, each a slot with spare capacity in one shared Int32Array that compacts once edits leave enough dead space, and a reverse row per vertex when directed; the only layout with addVertex, addEdge, and deleteEdge.
- `adjacencyMatrixGraph` → `AdjacencyMatrixGraph`: Immutable dense graph with one bit per vertex pair when unweighted or one Float64Array cell per pair when weighted, checked against GRAPH_MAX_MATRIX_BYTES before allocation; it cannot hold parallel edges.
- `breadthFirstSearch` → `BreadthFirstSearchResult`: Fewest-hops distance, parent, and visit order from one or more sources over any Adjacency, optionally stopping at a target; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because every reached row's walk costs its degree on compressed-sparse-row and adjacency-list, but O(n / 32 + d) on an unweighted adjacency-matrix and O(n) on a weighted one.
- `dijkstra` → `DijkstraResult`: Least total cost and parent from one or more sources over any Adjacency. Stops once all requested destinations settle, or searches all reachable vertices. Supports a per-edge cost override and checks non-negative costs on every edge walked. Uses knotkit/heap's indexed priority queue, with O((n + m) log n) time on compressed-sparse-row and adjacency-list, plus O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one for the row walks.
- `topologicalOrder` → `TopologicalOrderResult`: Kahn's algorithm over a directed Adjacency, returning an order or one directed cycle as a result rather than a throw; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because it walks every row.
- `connectedComponents` → `ConnectedComponentsResult`: Component count and a label per vertex for an undirected Adjacency, labels numbered by each component's smallest vertex, every isolated or closed grid cell a component of its own; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one.
- `floydWarshall` → `FloydWarshallResult`: Every pairwise shortest distance as a row-major n × n Float64Array, or a vertex on a negative cycle; runs on every layout and allocates its own 8n²-byte matrix, so it does not decide the storage; O(n³) time plus one walk of every row, and a Bellman-Ford pass over the rows when a cycle is negative.
- `path` → `Int32Array | undefined`: The vertices from a source to a target, read back from a breadthFirstSearch or dijkstra result; O(path length).
- `gridAdjacency` → `GridAdjacency`: An Adjacency over a rows × columns board with 4 or 8 moves per cell, closed cells, and refused moves, computed on demand rather than stored.
Pick the layout by these rules:
- `compressedSparseRowGraph` (kind 'compressed-sparse-row') when the edge set is known when you build the graph, whatever its density
- `adjacencyListGraph` (kind 'adjacency-list') when edges or vertices arrive after the graph is built
- `adjacencyMatrixGraph` (kind 'adjacency-matrix') when no vertex pair repeats an edge, at least 5% of vertex pairs are edges, you probe hasEdge, and n² / 8 bytes (8n² weighted) fit in 256 MiB
Use something else when:
- merge groups and ask whether two items are connected, without keeping the edges → knotkit/disjoint-set
- a visited flag per vertex you already index by number → a pre-sized Uint8Array
- a graph keyed by strings with attributes on every node and edge, or a format such as GraphML → graphology
- maximum flow, matching, minimum spanning trees, or strongly connected components → Effect's Graph module, until a caller moves one of them here
- an ordered frontier of your own, such as A* with a heuristic → knotkit/heap
Errors are GraphInvalidInputError or GraphParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/graph/wire` (serializeGraph, deserializeGraph).
Full page: https://knotkit.jkomyno.dev/modules/graph.md
Types: node_modules/knotkit/graph/ and https://knotkit.jkomyno.dev/reference/knotkit/graph/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/graph/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/graph/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/graph/knotkit.capability.json)suggest a change to the source record
# knotkit/hash
> Computes deterministic non-cryptographic XXH64 hashes, identical across browsers, Node.js, and Bun
## Use
[Section titled “Use”](#use)
```ts
import { xxh64 } from 'knotkit/hash'
const hash = xxh64()
const digest = hash.string('hello')
digest // 0x26c7_827d_889f_6da3n
hash.encodeHex(digest) // '26c7827d889f6da3'
// Uint8Array [0x26, 0xc7, 0x82, 0x7d, 0x88, 0x9f, 0x6d, 0xa3]
hash.encode(digest)
```
hash.ts●
ResetEditRun
```
```
```ts
const seeded = xxh64(0x0123_4567_89ab_cdefn)
seeded.bytes(Uint8Array.of(1, 2, 3))
seeded.uint32(42)
seeded.uint64(42n)
const state = seeded.create()
state.update(new TextEncoder().encode('hel'))
state.update(new TextEncoder().encode('lo'))
state.digest() // same as seeded.string('hello')
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* fingerprint bytes, text, or an unsigned integer the same way in every browser, Node.js, and Bun runtime
* shard keys across buckets or deduplicate records by a cheap fingerprint
* hash table keys without allocating or retaining a copy of the input
* reproduce earlier digests in a later process from a persisted algorithm version and seed
* hash a large payload chunk by chunk without holding it all in memory
## Worked example
[Section titled “Worked example”](#worked-example)
Inputs swept6464Reset
* XXH64 of "Knotkit!" at seed 0: c5398de0ce53a5f6.
* Flipping each input bit in turn changed between 26 and 41 digest bits.
* Across 4,096 one-bit flips of 64 inputs: mean 32.0 changed bits, SD 4.1. A fair coin per bit gives 32 and 4.
* Use this deterministic fingerprint to identify bytes. Use a cryptographic hash for adversarial inputs.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/hash/demo.ts) against `knotkit/hash` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`xxh64`](/reference/knotkit/hash/functions/xxh64/) | `ScalarHash<'xxh64', bigint, bigint>` | Frozen one-shot XXH64 value over bytes, text, \`uint32\`, and \`uint64\`, plus \`create()\` for an independent incremental byte state; the seed defaults to \`0n\`. |
| [`hashFromIdentity`](/reference/knotkit/hash/functions/hashfromidentity/) | `ScalarHash<'xxh64', bigint, bigint>` | Restore the current implementation matching a validated hash identity, so a persisted version and seed reproduce the same digests. |
Cost per member. Open a row for every operation.
`xxh64` 14 members
| Member | Cost |
| ------------ | ---- |
| `kind` | O(1) |
| `version` | O(1) |
| `seed` | O(1) |
| `bytes` | O(n) |
| `string` | O(n) |
| `uint32` | O(1) |
| `uint64` | O(1) |
| `bytesInto` | O(n) |
| `stringInto` | O(n) |
| `uint32Into` | O(1) |
| `uint64Into` | O(1) |
| `create` | O(1) |
| `encode` | O(1) |
| `encodeHex` | O(1) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `HashInvalidInputError` or `HashParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `HashInvalidInputError`
`INVALID_SEED`
* `HashParseError`
`INVALID_BYTES` `INVALID_STRING` `INVALID_UINT32` `INVALID_UINT64` `INVALID_CHUNK` `INVALID_OUTPUT` `INVALID_DIGEST` `INPUT_TOO_LONG` `STATE_FINALIZED` `INVALID_SHAPE` `UNKNOWN_KIND` `UNSUPPORTED_VERSION`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/hash/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeHashIdentity`, `deserializeHashIdentity`
* Formats
json
* Compatibility
identity-versioned; deserializeHashIdentity rejects an identity whose version is not HASH_IDENTITY_VERSION, which changes only when the digest mapping changes, never with a release, envelope v
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------- |
| hash a password, sign a message, or authenticate data with a secret | crypto.subtle from Web Crypto |
| resist collisions from an adversary who chooses the input | SHA-256 through crypto.subtle in Web Crypto |
| count distinct values, or estimate their frequencies, in bounded memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| checksum a large artifact at maximum throughput | the xxhash-wasm package, which runs the same algorithm in WebAssembly |
| persist a whole data structure and re-read it later | the structure package's serialize function |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/hash/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/hash/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/hashCopy prompt
```
Use knotkit/hash for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/hash'.
Exports:
- `xxh64` → `ScalarHash<'xxh64', bigint, bigint>`: Frozen one-shot XXH64 value over bytes, text, `uint32`, and `uint64`, plus `create()` for an independent incremental byte state; the seed defaults to `0n`.
- `hashFromIdentity` → `ScalarHash<'xxh64', bigint, bigint>`: Restore the current implementation matching a validated hash identity, so a persisted version and seed reproduce the same digests.
Use something else when:
- hash a password, sign a message, or authenticate data with a secret → crypto.subtle from Web Crypto
- resist collisions from an adversary who chooses the input → SHA-256 through crypto.subtle in Web Crypto
- count distinct values, or estimate their frequencies, in bounded memory → knotkit/scalar-sketch
- checksum a large artifact at maximum throughput → the xxhash-wasm package, which runs the same algorithm in WebAssembly
- persist a whole data structure and re-read it later → the structure package's serialize function
Errors are HashInvalidInputError or HashParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/hash/wire` (serializeHashIdentity, deserializeHashIdentity).
Full page: https://knotkit.jkomyno.dev/modules/hash.md
Types: node_modules/knotkit/hash/ and https://knotkit.jkomyno.dev/reference/knotkit/hash/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/hash/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/hash/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/hash/knotkit.capability.json)suggest a change to the source record
# knotkit/heap
> Binary and k-ary min/max heaps plus indexed priority queues, ordered by comparator you supply.
Four structures in one module: a binary heap, a k-ary heap, and an indexed priority queue over each. The first two hold values and answer “what is the best remaining item”. The priority queues hold keyed entries and answer it when a resident entry’s key changes, which is the case Dijkstra, Prim, and A\* are built on.
time O(n) build, O(log n) push/pop, O(1) peek · space O(n), or O(n) plus a position index · Floyd's bottom-up heapify; updateKey is O(log n) through the index, never a search
The distinction that matters: a heap cannot find an entry it is holding, so re-keying one costs a linear search and a remove. An indexed priority queue keeps a position index, so `updateKey(key, value)` sifts in place. That is an algorithmic-class difference, and it is why the measured key-update comparison is **272× faster than `heap-js` linear remove plus push**.
## Use
[Section titled “Use”](#use)
```ts
import { minBinaryHeap, minPriorityQueue, numberOrder } from 'knotkit/heap'
const heap = minBinaryHeap(numberOrder, [5, 8, 3])
heap.pop() // 3
const largest = minBinaryHeap(numberOrder, [5, 8, 3])
if (7 > largest.peek()) {
largest.replaceRoot(7) // returns 3; a fixed-size top-k
}
const queue = minPriorityQueue(numberOrder, [
[5, 'render'],
[1, 'parse'],
[3, 'layout'],
])
queue.updateKey(0, 'layout') // sifts in place, no search
queue.peek() // 'layout'
```
To keep the three largest values, hold a **min** heap and admit only values that beat its root: an inverted order is what makes an eviction structure out of a priority structure.
## Which layout, and why
[Section titled “Which layout, and why”](#which-layout-and-why)
The `kind` table on this page carries the predicates; the short version is the operation mix.
| If the workload is… | Choose | Because |
| ------------------------------------------------ | --------------------------------------- | ------------------------------------------------------------------ |
| pops at least as frequent as pushes, values only | `minBinaryHeap` / `maxBinaryHeap` | fewest comparisons per sift level at the same depth |
| pushes far outnumber pops, values only | `minKHeap` / `maxKHeap` with `k = 4` | a flatter tree pays `k` comparisons over fewer levels |
| resident values are re-keyed | `minPriorityQueue` / `maxPriorityQueue` | O(1) lookup and an in-place sift; a heap cannot find its own entry |
| keys are dense integers and re-keying dominates | `denseIntegerMinPriorityQueue` | no value-to-index registry at all |
Every layout, with the rule for choosing it:
| Factory | Choose when | Cost |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `minBinaryHeap`kind `binary-min` | the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count | 2 comparisons per sift-down level, ceil(log2 n) levels |
| `maxBinaryHeap`kind `binary-max` | the caller needs the largest value first and only pushes and pops values | 2 comparisons per sift-down level, ceil(log2 n) levels |
| `minKHeap`kind `k-min` | pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per level | k comparisons per sift level, log_k n levels |
| `maxKHeap`kind `k-max` | pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value first | k comparisons per sift level, log_k n levels |
| `minPriorityQueue`kind `binary-priority-queue-min` | resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count | 2 comparisons per sift level plus one Map lookup per key read |
| `maxPriorityQueue`kind `binary-priority-queue-max` | resident values must be re-keyed in place and the caller needs the largest key first | 2 comparisons per sift level plus one Map lookup per key read |
| `minKPriorityQueue`kind `k-priority-queue-min` | decrease-key calls outnumber pops and n is at or above 10,000 | k comparisons per sift level, log_k n levels, plus one Map lookup per key read |
| `maxKPriorityQueue`kind `k-priority-queue-max` | decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key first | k comparisons per sift level, log_k n levels, plus one Map lookup per key read |
| `denseIntegerMinPriorityQueue`kind `dense-integer-priority-queue-min` | numeric keys require resident decrease-key and values index a known fixed dense integer domain | O(capacity) space with constant-time direct position lookup and two comparisons per sift-down level |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/heap/README.md#performance)
A wider arity is a trade, not an upgrade: it makes each level more expensive and each path shorter.
## Count the comparisons
[Section titled “Count the comparisons”](#count-the-comparisons)
Drag the arity and the heap size: every change reruns the module’s own demo against `knotkit/heap` in your browser, counting comparator calls by wrapping the `Order` the heap takes as a parameter. The defaults reproduce the README figure.
Largest heap2,04811Children per node44Reset
* On 2,048 seeded keys, drain comparisons per pop are 9.7 / 14.9 for 2 / 4 children.
* Indexed updates move item 2047 to priority -2048 without inserting a second entry.
* The plots count comparator calls after construction.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/heap/demo.ts) against `knotkit/heap` in your browser; the defaults reproduce the README figure.
A wider heap pays more comparisons per pop and fewer per decrease. The right arity follows your workload’s mix of the two, which is why the module states it as a rule rather than a default.
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Heaps persist through a second entrypoint, `knotkit/heap/wire`, which is where the parser lives; importing `knotkit/heap` never loads it. Both binary and JSON formats are versioned, and a decoded structure is checked against the heap invariant rather than trusted — a truncated artifact fails with a code (`MISSING_NODES`, `HEAP_INVARIANT_VIOLATION`) instead of producing a heap that quietly lies about its order.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------ |
| [`minBinaryHeap`](/reference/knotkit/heap/functions/minbinaryheap/) | `BinaryHeap` | Binary min heap over any order; O(n) Floyd build from an iterable. |
| [`maxBinaryHeap`](/reference/knotkit/heap/functions/maxbinaryheap/) | `BinaryHeap` | Binary max heap over any order; O(n) Floyd build from an iterable. |
| [`minKHeap`](/reference/knotkit/heap/functions/minkheap/) | `KHeap` | k-ary min heap; \`k\` is the arity and is taken first. |
| [`maxKHeap`](/reference/knotkit/heap/functions/maxkheap/) | `KHeap` | k-ary max heap; \`k\` is the arity and is taken first. |
| [`minPriorityQueue`](/reference/knotkit/heap/functions/minpriorityqueue/) | `BinaryPriorityQueue` | Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key. |
| [`maxPriorityQueue`](/reference/knotkit/heap/functions/maxpriorityqueue/) | `BinaryPriorityQueue` | Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key. |
| [`minKPriorityQueue`](/reference/knotkit/heap/functions/minkpriorityqueue/) | `KPriorityQueue` | Indexed k-ary min queue; \`k\` is the arity and is taken first. |
| [`maxKPriorityQueue`](/reference/knotkit/heap/functions/maxkpriorityqueue/) | `KPriorityQueue` | Indexed k-ary max queue; \`k\` is the arity and is taken first. |
| [`makeOrder`](/reference/knotkit/heap/functions/makeorder/) | `Order` | Build an order from a \`(a, b) => number\` comparator, short-circuiting on referential equality. |
| [`reverseOrder`](/reference/knotkit/heap/functions/reverseorder/) | `Order` | Flip an order's direction, turning a min-comparator into a max-comparator. |
| [`mapInputOrder`](/reference/knotkit/heap/functions/mapinputorder/) | `Order` | Derive an order on \`B\` by projecting each value to an \`A\` first. |
| [`denseIntegerMinPriorityQueue`](/reference/knotkit/heap/functions/denseintegerminpriorityqueue/) | `DenseIntegerPriorityQueue` | Preallocate a known dense integer domain for a numeric min queue with direct-index decrease-key. |
Cost per member. Open a row for every operation.
`minBinaryHeap` 8 members
| Member | Cost |
| ------------------- | -------- |
| `peek` | O(1) |
| `pop` | O(log n) |
| `replaceRoot` | O(log n) |
| `push` | O(log n) |
| `size` | O(1) |
| `clear` | O(1) |
| `values` | O(n) |
| `[Symbol.iterator]` | O(n) |
`maxBinaryHeap` 8 members
| Member | Cost |
| ------------------- | -------- |
| `peek` | O(1) |
| `pop` | O(log n) |
| `replaceRoot` | O(log n) |
| `push` | O(log n) |
| `size` | O(1) |
| `clear` | O(1) |
| `values` | O(n) |
| `[Symbol.iterator]` | O(n) |
`minKHeap` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(k log_k n) |
| `replaceRoot` | O(k log_k n) |
| `push` | O(log_k n) |
| `size` | O(1) |
| `clear` | O(1) |
| `values` | O(n) |
| `[Symbol.iterator]` | O(n) |
`maxKHeap` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(k log_k n) |
| `replaceRoot` | O(k log_k n) |
| `push` | O(log_k n) |
| `size` | O(1) |
| `clear` | O(1) |
| `values` | O(n) |
| `[Symbol.iterator]` | O(n) |
`minPriorityQueue` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(log n) |
| `push` | O(log n) |
| `updateKey` | O(log n) |
| `keyOf` | O(1) average |
| `clear` | O(n) |
| `entries` | O(n) |
| `[Symbol.iterator]` | O(n) |
`maxPriorityQueue` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(log n) |
| `push` | O(log n) |
| `updateKey` | O(log n) |
| `keyOf` | O(1) average |
| `clear` | O(n) |
| `entries` | O(n) |
| `[Symbol.iterator]` | O(n) |
`minKPriorityQueue` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(k log_k n) |
| `push` | O(log_k n) |
| `updateKey` | O(k log_k n) |
| `keyOf` | O(1) average |
| `clear` | O(n) |
| `entries` | O(n) |
| `[Symbol.iterator]` | O(n) |
`maxKPriorityQueue` 8 members
| Member | Cost |
| ------------------- | ------------ |
| `peek` | O(1) |
| `pop` | O(k log_k n) |
| `push` | O(log_k n) |
| `updateKey` | O(k log_k n) |
| `keyOf` | O(1) average |
| `clear` | O(n) |
| `entries` | O(n) |
| `[Symbol.iterator]` | O(n) |
`denseIntegerMinPriorityQueue` 14 members
| Member | Cost |
| ------------------- | --------------------- |
| `construction` | O(capacity + entries) |
| `capacity` | O(1) |
| `size` | O(1) |
| `has` | O(1) |
| `keyOf` | O(1) |
| `peek` | O(1) |
| `peekEntry` | O(1) |
| `push` | O(log n) |
| `pop` | O(log n) |
| `popEntry` | O(log n) |
| `updateKey` | O(log n) |
| `clear` | O(n) |
| `entries` | O(n) |
| `[Symbol.iterator]` | O(n) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `HeapInvalidInputError` or `HeapParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `HeapInvalidInputError`
`EMPTY` `INVALID_ARITY` `INVALID_CAPACITY` `DUPLICATE_VALUE` `INVALID_VALUE`
* `HeapParseError`
`VALUE_NOT_FOUND` `FOREIGN_STRUCTURE` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_NODES` `MISSING_ENTRIES` `HEAP_INVARIANT_VIOLATION` `INVALID_ELEMENT` `INVALID_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`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| sort a fixed array once | Array.prototype.sort with a comparator |
| an exact set or map, with no ordering | Set, Map |
| remove an arbitrary resident entry, or cancel a queued task | a Map plus a heap of stale entries re-checked on pop; delete is not implemented |
| track which elements are connected, and merge groups | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| count distinct values or estimate frequencies in bounded memory | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknown | minPriorityQueue (binary-priority-queue-min) from knotkit/heap |
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/heapCopy prompt
```
Use knotkit/heap for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/heap'.
Exports:
- `minBinaryHeap` → `BinaryHeap`: Binary min heap over any order; O(n) Floyd build from an iterable.
- `maxBinaryHeap` → `BinaryHeap`: Binary max heap over any order; O(n) Floyd build from an iterable.
- `minKHeap` → `KHeap`: k-ary min heap; `k` is the arity and is taken first.
- `maxKHeap` → `KHeap`: k-ary max heap; `k` is the arity and is taken first.
- `minPriorityQueue` → `BinaryPriorityQueue`: Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key.
- `maxPriorityQueue` → `BinaryPriorityQueue`: Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key.
- `minKPriorityQueue` → `KPriorityQueue`: Indexed k-ary min queue; `k` is the arity and is taken first.
- `maxKPriorityQueue` → `KPriorityQueue`: Indexed k-ary max queue; `k` is the arity and is taken first.
- `makeOrder` → `Order`: Build an order from a `(a, b) => number` comparator, short-circuiting on referential equality.
- `reverseOrder` → `Order`: Flip an order's direction, turning a min-comparator into a max-comparator.
- `mapInputOrder` → `Order`: Derive an order on `B` by projecting each value to an `A` first.
- `denseIntegerMinPriorityQueue` → `DenseIntegerPriorityQueue`: Preallocate a known dense integer domain for a numeric min queue with direct-index decrease-key.
Pick the layout by these rules:
- `minBinaryHeap` (kind 'binary-min') when the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count
- `maxBinaryHeap` (kind 'binary-max') when the caller needs the largest value first and only pushes and pops values
- `minKHeap` (kind 'k-min') when pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per level
- `maxKHeap` (kind 'k-max') when pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value first
- `minPriorityQueue` (kind 'binary-priority-queue-min') when resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count
- `maxPriorityQueue` (kind 'binary-priority-queue-max') when resident values must be re-keyed in place and the caller needs the largest key first
- `minKPriorityQueue` (kind 'k-priority-queue-min') when decrease-key calls outnumber pops and n is at or above 10,000
- `maxKPriorityQueue` (kind 'k-priority-queue-max') when decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key first
- `denseIntegerMinPriorityQueue` (kind 'dense-integer-priority-queue-min') when numeric keys require resident decrease-key and values index a known fixed dense integer domain
Inputs and their sources:
- ordering: `Order` from `knotkit/heap`
- ordering on restore, which no artifact carries: `Order` from `knotkit/heap`
Use something else when:
- sort a fixed array once → Array.prototype.sort with a comparator
- an exact set or map, with no ordering → Set, Map
- remove an arbitrary resident entry, or cancel a queued task → a Map plus a heap of stale entries re-checked on pop; delete is not implemented
- track which elements are connected, and merge groups → knotkit/disjoint-set
- count distinct values or estimate frequencies in bounded memory → knotkit/scalar-sketch
- decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknown → minPriorityQueue (binary-priority-queue-min) from knotkit/heap
Errors are HeapInvalidInputError or HeapParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/heap/wire` (serializeHeap, deserializeHeap, serializeHeapJson, deserializeHeapJson, serializePriorityQueue, deserializePriorityQueue, serializePriorityQueueJson, deserializePriorityQueueJson).
Full page: https://knotkit.jkomyno.dev/modules/heap.md
Types: node_modules/knotkit/heap/ and https://knotkit.jkomyno.dev/reference/knotkit/heap/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/heap/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/heap/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/apps/docs/src/content/docs/modules/heap.mdx)suggest a change to the source record
# knotkit/hypothesis-test
> Computes t-test, ANOVA, rank-test, goodness-of-fit, and exact-test p-values for counts, samples, and contingency tables
## Use
[Section titled “Use”](#use)
```ts
import {
Probability,
binomialTest,
chiSquaredGoodnessOfFitTest,
kruskalWallisTest,
mannWhitneyUTest,
oneWayAnova,
welchTTest,
} from 'knotkit/hypothesis-test'
const fairCoin = binomialTest(63, 100)
const ratio = binomialTest(682, 925, {
successProbability: Probability.make(0.75),
})
const fit = chiSquaredGoodnessOfFitTest([23, 21, 30, 26], [0.25, 0.25, 0.25, 0.25].map(Probability.make))
const means = welchTTest([2.1, 3.4, 1.9, 5.6], [1.2, 2.9, 3.1, 0.8, 2.2], {
alternative: 'greater',
})
const groups = oneWayAnova([
[6, 8, 4, 5],
[8, 12, 9, 11],
[13, 9, 11, 8],
])
const ranks = mannWhitneyUTest([19, 22, 16, 29, 24], [20, 11, 17, 12])
const medians = kruskalWallisTest([
[2.9, 3.0, 2.5, 2.6],
[3.8, 2.7, 4.0, 2.4],
[2.8, 3.4, 3.7, 2.2],
])
```
hypothesis-test.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* compute a chi-square p-value for observed counts against category probabilities
* test whether draws fit a continuous distribution with Kolmogorov-Smirnov
* compare the distributions of two samples
* test one sample mean, two sample means, or paired measurements with a t-test, or three or more group means with a one-way ANOVA, or compare samples by rank with Mann-Whitney U, Wilcoxon signed-rank, or Kruskal-Wallis
* test an observed success count using an exact binomial p-value
* calculate a two-sided or directional Fisher exact p-value for a 2-by-2 table
## Try it
[Section titled “Try it”](#try-it)
ScenarioDefaultReset
* Compare 8 clustered observations against Uniform(0, 1).
* Largest CDF gap D = 0.520. Two-sided p = 0.015 (exact).
* Compare 8 spread observations against Uniform(0, 1).
* Largest CDF gap D = 0.080. Two-sided p = 1.000 (exact).
* Use a one-sample Kolmogorov-Smirnov test for a fully specified continuous null.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/hypothesis-test/demo.ts) against `knotkit/hypothesis-test` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ---------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`chiSquaredGoodnessOfFitTest`](/reference/knotkit/hypothesis-test/functions/chisquaredgoodnessoffittest/) | `ChiSquaredGoodnessOfFitTestResult` | Pearson goodness of fit with optional adjacent pooling. Construct category probabilities with Probability.make. Degrees of freedom above CHI_SQUARED_MAX_DEGREES_OF_FREEDOM surface DistributionInvalidInputError. |
| [`kolmogorovSmirnovTest`](/reference/knotkit/hypothesis-test/functions/kolmogorovsmirnovtest/) | `KolmogorovSmirnovTestResult` | Compare a sample with a continuous distribution, using the exact null distribution at fewer than 100 observations without repeated values. |
| [`twoSampleKolmogorovSmirnovTest`](/reference/knotkit/hypothesis-test/functions/twosamplekolmogorovsmirnovtest/) | `TwoSampleKolmogorovSmirnovTestResult` | Compare two samples, using the exact null distribution below 10,000 pairs without repeated pooled values. |
| [`oneSampleTTest`](/reference/knotkit/hypothesis-test/functions/onesamplettest/) | `OneSampleTTestResult` | Student's t-test of a sample mean against an expected mean, as scipy.stats.ttest_1samp. A constant sample throws ZERO_VARIANCE where SciPy returns NaN. |
| [`twoSampleTTest`](/reference/knotkit/hypothesis-test/functions/twosamplettest/) | `TwoSampleTTestResult` | Pooled-variance t-test of two independent samples, as scipy.stats.ttest_ind with equal_var=True. Choose welchTTest when the variances may differ. |
| [`welchTTest`](/reference/knotkit/hypothesis-test/functions/welchttest/) | `WelchTTestResult` | Unequal-variance t-test with Welch-Satterthwaite degrees of freedom, as scipy.stats.ttest_ind with equal_var=False. |
| [`pairedTTest`](/reference/knotkit/hypothesis-test/functions/pairedttest/) | `PairedTTestResult` | t-test of paired measurements, as scipy.stats.ttest_rel: oneSampleTTest of the differences against zero. |
| [`oneWayAnova`](/reference/knotkit/hypothesis-test/functions/onewayanova/) | `OneWayAnovaResult` | One-way ANOVA F-test of k >= 2 independent groups, as scipy.stats.f_oneway. The p-value is the upper tail, so it takes no alternative. |
| [`mannWhitneyUTest`](/reference/knotkit/hypothesis-test/functions/mannwhitneyutest/) | `MannWhitneyUTestResult` | Mann-Whitney U rank test of two independent samples, as scipy.stats.mannwhitneyu. Exact without ties when the smaller sample has at most 8 values, else a tie-corrected normal approximation. All-equal values throw ZERO_VARIANCE where SciPy returns NaN. |
| [`wilcoxonSignedRankTest`](/reference/knotkit/hypothesis-test/functions/wilcoxonsignedranktest/) | `WilcoxonSignedRankTestResult` | Wilcoxon signed-rank test of paired differences, as scipy.stats.wilcoxon with zero_method wilcox: zeros are dropped and ties take average ranks. All-zero differences throw ZERO_VARIANCE. |
| [`kruskalWallisTest`](/reference/knotkit/hypothesis-test/functions/kruskalwallistest/) | `KruskalWallisTestResult` | Tie-corrected Kruskal-Wallis H-test of k >= 2 independent groups, as scipy.stats.kruskal, with a chi-squared upper-tail p-value. It takes no alternative. |
| [`binomialTest`](/reference/knotkit/hypothesis-test/functions/binomialtest/) | `BinomialTestResult` | Test a success count under a binomial null. Construct the null successProbability with Probability.make. Trial counts above BINOMIAL_MAX_TRIALS surface DistributionInvalidInputError. |
| [`fisherExactTest`](/reference/knotkit/hypothesis-test/functions/fisherexacttest/) | `FisherExactTestResult` | Test the top-left count of a 2-by-2 table under its fixed margins. Tables above HYPERGEOMETRIC_MAX_POPULATION_SIZE surface DistributionInvalidInputError. |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `HypothesisTestInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `EMPTY_SAMPLE` `NON_FINITE_SAMPLE` `INVALID_COUNT` `INVALID_PROBABILITIES` `LENGTH_MISMATCH` `TOO_FEW_CATEGORIES` `INVALID_TABLE` `SUCCESSES_EXCEED_TRIALS` `INVALID_DEGREES_OF_FREEDOM` `ZERO_TOTAL_COUNT` `INVALID_OPTION` `TOO_SMALL_SAMPLE` `TOO_FEW_GROUPS` `ZERO_VARIANCE`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| evaluate a probability or draw from a named distribution | [`knotkit/distribution`](/modules/distribution/) |
| analyze regression, multi-factor or repeated-measures ANOVA, or paired-group rank tests such as Friedman | SciPy or R |
| test chi-squared independence or Fisher exact on a larger contingency table | SciPy or R |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/hypothesis-test/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/hypothesis-test/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/hypothesis-testCopy prompt
```
Use knotkit/hypothesis-test for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/hypothesis-test'.
Exports:
- `chiSquaredGoodnessOfFitTest` → `ChiSquaredGoodnessOfFitTestResult`: Pearson goodness of fit with optional adjacent pooling. Construct category probabilities with Probability.make. Degrees of freedom above CHI_SQUARED_MAX_DEGREES_OF_FREEDOM surface DistributionInvalidInputError.
- `kolmogorovSmirnovTest` → `KolmogorovSmirnovTestResult`: Compare a sample with a continuous distribution, using the exact null distribution at fewer than 100 observations without repeated values.
- `twoSampleKolmogorovSmirnovTest` → `TwoSampleKolmogorovSmirnovTestResult`: Compare two samples, using the exact null distribution below 10,000 pairs without repeated pooled values.
- `oneSampleTTest` → `OneSampleTTestResult`: Student's t-test of a sample mean against an expected mean, as scipy.stats.ttest_1samp. A constant sample throws ZERO_VARIANCE where SciPy returns NaN.
- `twoSampleTTest` → `TwoSampleTTestResult`: Pooled-variance t-test of two independent samples, as scipy.stats.ttest_ind with equal_var=True. Choose welchTTest when the variances may differ.
- `welchTTest` → `WelchTTestResult`: Unequal-variance t-test with Welch-Satterthwaite degrees of freedom, as scipy.stats.ttest_ind with equal_var=False.
- `pairedTTest` → `PairedTTestResult`: t-test of paired measurements, as scipy.stats.ttest_rel: oneSampleTTest of the differences against zero.
- `oneWayAnova` → `OneWayAnovaResult`: One-way ANOVA F-test of k >= 2 independent groups, as scipy.stats.f_oneway. The p-value is the upper tail, so it takes no alternative.
- `mannWhitneyUTest` → `MannWhitneyUTestResult`: Mann-Whitney U rank test of two independent samples, as scipy.stats.mannwhitneyu. Exact without ties when the smaller sample has at most 8 values, else a tie-corrected normal approximation. All-equal values throw ZERO_VARIANCE where SciPy returns NaN.
- `wilcoxonSignedRankTest` → `WilcoxonSignedRankTestResult`: Wilcoxon signed-rank test of paired differences, as scipy.stats.wilcoxon with zero_method wilcox: zeros are dropped and ties take average ranks. All-zero differences throw ZERO_VARIANCE.
- `kruskalWallisTest` → `KruskalWallisTestResult`: Tie-corrected Kruskal-Wallis H-test of k >= 2 independent groups, as scipy.stats.kruskal, with a chi-squared upper-tail p-value. It takes no alternative.
- `binomialTest` → `BinomialTestResult`: Test a success count under a binomial null. Construct the null successProbability with Probability.make. Trial counts above BINOMIAL_MAX_TRIALS surface DistributionInvalidInputError.
- `fisherExactTest` → `FisherExactTestResult`: Test the top-left count of a 2-by-2 table under its fixed margins. Tables above HYPERGEOMETRIC_MAX_POPULATION_SIZE surface DistributionInvalidInputError.
Use something else when:
- evaluate a probability or draw from a named distribution → knotkit/distribution
- analyze regression, multi-factor or repeated-measures ANOVA, or paired-group rank tests such as Friedman → SciPy or R
- test chi-squared independence or Fisher exact on a larger contingency table → SciPy or R
Errors are HypothesisTestInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/hypothesis-test.md
Types: node_modules/knotkit/hypothesis-test/ and https://knotkit.jkomyno.dev/reference/knotkit/hypothesis-test/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/hypothesis-test/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/hypothesis-test/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/hypothesis-test/knotkit.capability.json)suggest a change to the source record
# knotkit/interval-index
> Indexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range
## Use
[Section titled “Use”](#use)
```ts
import { augmentedRedBlackIntervalIndex } from 'knotkit/interval-index'
import { compareBytes } from 'knotkit/key-encoding'
const key = (text: string): Uint8Array => new TextEncoder().encode(text)
// Level-0 tables, each routed by its [minKey, maxKey] fence pointers.
const tables = augmentedRedBlackIntervalIndex(compareBytes)
const first = tables.add(key('apple'), key('cherry'), 'sst-1')
tables.add(key('banana'), key('date'), 'sst-2')
tables.add(key('fig'), key('grape'), 'sst-3')
// A point read probes every table whose fences hold the key, oldest start first.
const probes = [...tables.atPoint(key('blueberry'))].map((entry) => entry.value) // ['sst-1', 'sst-2']
// A compaction of [cherry, fig] must read every table overlapping it; touching endpoints overlap.
const inputs = [...tables.overlapping(key('cherry'), key('fig'))].map((entry) => entry.value) // ['sst-1', 'sst-2', 'sst-3']
// Compaction retires a table by the id add returned.
tables.delete(first) // true
tables.size // 2
```
interval-index.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* find which SSTables' \[minKey, maxKey] fence pointers can hold a key on a level-0 read
* select every table in the next level whose key range overlaps a compaction input
* find every booking, lease, or time window that covers a moment or overlaps a span
* keep a set of ranges that are added and removed by id while answering overlap queries
* match ranges whose endpoints are byte strings, numbers, or any keys with a total order
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `augmentedRedBlackIntervalIndex`kind `augmented-red-black-tree` | intervals are added and deleted dynamically (such as L0 tables arriving on flush and leaving on compaction) and n exceeds a few hundred | one tree node with three links, a color, and a subtree maximum end per entry; 4.1 ms against sorted-array's 39.5 ms for 1,000 rounds of one flush, four point reads, and a compaction every fourth round over 1,000 tables, and 1.6 to 1.7 times slower than sorted-array on static queries over 1,000 to 10,000 tables |
| `sortedArrayIntervalIndex`kind `sorted-array` | the interval set is built once or changes infrequently relative to queries (such as immutable LSM level manifests) | two array slots per entry; 0.43 ms for 1,000 point queries over 10,000 tables against 0.72 ms for augmented-red-black-tree, but every query after an out-of-order add or a deletion first pays an O(n log n) or O(n) rebuild, and a single long interval near the start can make a query scan every entry after it |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/interval-index/README.md#performance)
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`augmentedRedBlackIntervalIndex`](/reference/knotkit/interval-index/functions/augmentedredblackintervalindex/) | `IntervalIndex` | Red-black tree keyed by (start, id) with each node's subtree maximum end, maintained on every insertion, deletion, and rotation, plus a map from id to node. |
| [`sortedArrayIntervalIndex`](/reference/knotkit/interval-index/functions/sortedarrayintervalindex/) | `IntervalIndex` | One array of entries sorted by (start, id) with a parallel running maximum of end, rebuilt by the first query after an out-of-order add or a deletion, plus a map from id to entry. |
Cost per member. Open a row for every operation.
`augmentedRedBlackIntervalIndex` 10 members
| Member | Cost |
| ------------- | ----------------------------------------------- |
| `build` | O(n log n) |
| `size` | O(1) |
| `add` | O(log n) |
| `delete` | O(log n) |
| `has` | O(1) |
| `get` | O(1) |
| `atPoint` | O(min(n, (k + 1) log n)) for k entries reported |
| `overlapping` | O(min(n, (k + 1) log n)) for k entries reported |
| `entries` | O(n) |
| `clear` | O(1) |
`sortedArrayIntervalIndex` 10 members
| Member | Cost |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `build` | O(n log n) |
| `size` | O(1) |
| `add` | O(1) amortized; an add whose start sorts before the last stored start defers an O(n log n) rebuild to the next query |
| `delete` | O(1) amortized, O(n) when half the entries are deleted; nonempty queries rebuild prefix maxima in O(n) after deletions alone |
| `has` | O(1) |
| `get` | O(1) |
| `atPoint` | O(log n + m) once settled, where m counts entries from the first whose running maximum end reaches the query start to the last starting at or before the query end; k <= m <= n |
| `overlapping` | O(log n + m) once settled, where m counts entries from the first whose running maximum end reaches the query start to the last starting at or before the query end; k <= m <= n |
| `entries` | O(n) once settled |
| `clear` | O(1) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| --------- | ---------- | -------------------------------- |
| key order | `Order` | [`knotkit/heap`](/modules/heap/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `IntervalIndexInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_INTERVAL` `MODIFIED_DURING_ITERATION`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------ | ------------------------------------------------ |
| look up, rank, or scan single keys rather than ranges | [`knotkit/ordered-map`](/modules/ordered-map/) |
| membership or range counts over unsigned 32-bit integer ids | [`knotkit/bitset`](/modules/bitset/) |
| a compact immutable block of sorted byte-keyed entries with seeks | [`knotkit/sorted-block`](/modules/sorted-block/) |
| the longest stored prefix of a delimiter-separated key | [`knotkit/trie`](/modules/trie/) |
| overlap queries over rectangles or boxes in two or more dimensions | an R-tree library such as rbush |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/interval-index/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/interval-index/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/interval-indexCopy prompt
```
Use knotkit/interval-index for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/interval-index'.
Exports:
- `augmentedRedBlackIntervalIndex` → `IntervalIndex`: Red-black tree keyed by (start, id) with each node's subtree maximum end, maintained on every insertion, deletion, and rotation, plus a map from id to node.
- `sortedArrayIntervalIndex` → `IntervalIndex`: One array of entries sorted by (start, id) with a parallel running maximum of end, rebuilt by the first query after an out-of-order add or a deletion, plus a map from id to entry.
Pick the layout by these rules:
- `augmentedRedBlackIntervalIndex` (kind 'augmented-red-black-tree') when intervals are added and deleted dynamically (such as L0 tables arriving on flush and leaving on compaction) and n exceeds a few hundred
- `sortedArrayIntervalIndex` (kind 'sorted-array') when the interval set is built once or changes infrequently relative to queries (such as immutable LSM level manifests)
Inputs and their sources:
- key order: `Order` from `knotkit/heap`
Use something else when:
- look up, rank, or scan single keys rather than ranges → knotkit/ordered-map
- membership or range counts over unsigned 32-bit integer ids → knotkit/bitset
- a compact immutable block of sorted byte-keyed entries with seeks → knotkit/sorted-block
- the longest stored prefix of a delimiter-separated key → knotkit/trie
- overlap queries over rectangles or boxes in two or more dimensions → an R-tree library such as rbush
Errors are IntervalIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/interval-index.md
Types: node_modules/knotkit/interval-index/ and https://knotkit.jkomyno.dev/reference/knotkit/interval-index/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/interval-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/interval-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/interval-index/knotkit.capability.json)suggest a change to the source record
# knotkit/inverted-index
> Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
## Use
[Section titled “Use”](#use)
```ts
import { invertedIndex } from 'knotkit/inverted-index'
const issues = [
{ title: 'Fix login', labels: ['open', 'urgent'] },
{ title: 'Document setup', labels: [] },
{ title: 'Fix export', labels: ['urgent', 'urgent'] },
]
const index = invertedIndex(issues, (issue) => issue.labels)
index.size // 2 distinct labels
index.recordCount // 3 issues
Array.from(index.postings('urgent')) // [0, 2]
Array.from(index.postings('closed')) // []
const titles: string[] = []
index.forEachAny(['urgent', 'open'], (id) => titles.push(issues[id].title))
// titles holds ['Fix login', 'Fix export']
```
inverted-index.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* look up all records tagged with an exact key after reading the input once
* visit records carrying any requested tag once, in their original order
* group record positions by feature when a record can supply several features or repeat one
## Try it
[Section titled “Try it”](#try-it)
ScenarioDefaultReset
* Indexed 2048 records under 2 labels.
* The two posting lists have 86 entries and the union emits 64 unique IDs.
* Build the index once when repeated queries over fixed tags make a full scan wasteful.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/inverted-index/demo.ts) against `knotkit/inverted-index` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ----------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| [`invertedIndex`](/reference/knotkit/inverted-index/functions/invertedindex/) | `InvertedIndex` | Build once from an iterable and its key selector. Every query yields matching zero-based record positions in ascending order. |
Cost per member. Open a row for every operation.
`invertedIndex` 6 members
| Member | Cost |
| ------------- | ------------------------------------------------------------------------- |
| `size` | O(1) |
| `recordCount` | O(1) |
| `postings` | O(1) expected lookup and O(1) per ID |
| `keys` | O(1) per key |
| `entries` | O(1) per key and posting iterator, then O(1) per ID read |
| `forEachAny` | O(q × (u + 1)) time and O(q) workspace for q query keys and u visited IDs |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ------------------------------------------------------ | ---------------------------------------- | ------------ |
| exact keys for each input record and its zero-based ID | `(record: R, id: number) => Iterable` | `the caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `InvertedIndexInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `MAX_CAPACITY_EXCEEDED`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------- | ------------------------------------ |
| add or remove associations between queries | Map\> |
| match a delimiter-separated key by longest prefix | [`knotkit/trie`](/modules/trie/) |
| combine mutable sets of integer IDs | [`knotkit/bitset`](/modules/bitset/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/inverted-index/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/inverted-index/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#inverted-index).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/inverted-indexCopy prompt
```
Use knotkit/inverted-index for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/inverted-index'.
Exports:
- `invertedIndex` → `InvertedIndex`: Build once from an iterable and its key selector. Every query yields matching zero-based record positions in ascending order.
Inputs and their sources:
- exact keys for each input record and its zero-based ID: `(record: R, id: number) => Iterable` from `the caller`
Use something else when:
- add or remove associations between queries → Map>
- match a delimiter-separated key by longest prefix → knotkit/trie
- combine mutable sets of integer IDs → knotkit/bitset
Errors are InvertedIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/inverted-index.md
Types: node_modules/knotkit/inverted-index/ and https://knotkit.jkomyno.dev/reference/knotkit/inverted-index/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/inverted-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/inverted-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/inverted-index/knotkit.capability.json)suggest a change to the source record
# knotkit/key-encoding
> Encodes integers, doubles, byte strings, strings, and tuples of them as byte keys whose unsigned byte order matches the values' order
## Use
[Section titled “Use”](#use)
```ts
import { bytesPrefixEnd, compareBytes, decodeKeyTuple, encodeKeyTuple } from 'knotkit/key-encoding'
// (user key ascending, sequence number descending): the newest version of each key sorts first.
const rows: [userKey: string, sequence: bigint][] = [
['b', 1n],
['a', 2n],
['a', 7n],
]
const keys = rows.map(([userKey, sequence]) =>
encodeKeyTuple([
{ kind: 'string', value: userKey },
{ kind: 'uint64', value: sequence, direction: 'descending' },
]),
)
const order = keys.toSorted(compareBytes).map((key) => decodeKeyTuple(key).map((part) => part.value))
// [['a', 7n], ['a', 2n], ['b', 1n]]
// Every key under user 'a' lies in [prefix, end).
const prefix = encodeKeyTuple([{ kind: 'string', value: 'a' }])
const end = bytesPrefixEnd(prefix)
```
key-encoding.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* build a composite key such as (user id, timestamp) that a byte-ordered store sorts field by field
* sort one field of a composite key descending, such as newest version first, without a custom comparator
* store signed integers or doubles as keys that sort numerically rather than by their raw bytes
* scan every key that starts with a prefix by computing the range's exclusive upper bound
* compare or sort Uint8Array keys in the order memcmp, LevelDB, or IndexedDB uses
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `encodeBytesKey`kind `bytes` | the field is a Uint8Array whose keys must sort by the raw bytes, with a byte string sorting before every longer string it prefixes | length + 2 bytes, plus one byte per 0x00 in the value |
| `encodeStringKey`kind `string` | the field is a JavaScript string without unpaired surrogates and Unicode code point order is the order the caller needs | UTF-8 length + 2 bytes, plus one byte per U+0000; one TextEncoder pass per encode |
| `encodeUint32Key`kind `uint32` | the field is an integer in 0 .. 2^32 - 1 | 4 bytes |
| `encodeInt32Key`kind `int32` | the field is an integer in -2^31 .. 2^31 - 1 that can be negative | 4 bytes |
| `encodeUint64Key`kind `uint64` | the field is a bigint in 0n .. 2n \*\* 64n - 1n, such as a sequence number or a 64-bit id | 8 bytes |
| `encodeInt64Key`kind `int64` | the field is a bigint in -(2n \*\* 63n) .. 2n \*\* 63n - 1n that can be negative | 8 bytes |
| `encodeFloat64Key`kind `float64` | the field is a non-NaN number that is fractional or beyond the safe integers, and -0 and 0 may share one key | 8 bytes |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/key-encoding/README.md#performance)
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`encodeKeyTuple`](/reference/knotkit/key-encoding/functions/encodekeytuple/) | `Uint8Array` | Composite key over bytes, string, 32- and 64-bit integer, and float64 parts, each ascending or descending, ordered part by part under compareBytes with a prefix tuple first. |
| [`decodeKeyTuple`](/reference/knotkit/key-encoding/functions/decodekeytuple/) | `readonly KeyTuplePart[]` | Parts of an encodeKeyTuple key, each with an explicit direction; accepts exactly the bytes encodeKeyTuple writes. |
| [`compareBytes`](/reference/knotkit/key-encoding/functions/comparebytes/) | `-1 \| 0 \| 1` | Unsigned lexicographic order over Uint8Array keys, a proper prefix first; an Order\ for sorting and comparator-based structures. Does not validate its arguments. |
| [`commonPrefixLength`](/reference/knotkit/key-encoding/functions/commonprefixlength/) | `number` | Count of leading bytes two keys share, from 0 through the shorter length. Does not validate its arguments. |
| [`bytesPrefixEnd`](/reference/knotkit/key-encoding/functions/bytesprefixend/) | `Uint8Array \| undefined` | Smallest key greater than every key that starts with a prefix, the exclusive end of a prefix scan; undefined when the prefix is empty or all 0xff. |
| [`invertKeyBytes`](/reference/knotkit/key-encoding/functions/invertkeybytes/) | `Uint8Array` | Bitwise complement of every byte as a new array, reversing the order of keys of one length; a variable-length descending field needs encodeDescendingBytesKey. |
Cost per member. Open a row for every operation.
`encodeKeyTuple` 1 members
| Member | Cost |
| -------- | ---------------------------------- |
| `encode` | O(total key bytes), one allocation |
`decodeKeyTuple` 1 members
| Member | Cost |
| -------- | ------------------ |
| `decode` | O(total key bytes) |
`compareBytes` 1 members
| Member | Cost |
| --------- | --------------------------- |
| `compare` | O(shared prefix length + 1) |
`commonPrefixLength` 1 members
| Member | Cost |
| --------- | --------- |
| `compute` | O(result) |
`bytesPrefixEnd` 1 members
| Member | Cost |
| --------- | -------------------------------- |
| `compute` | O(prefix length), one allocation |
`invertKeyBytes` 1 members
| Member | Cost |
| --------- | ------------------------- |
| `compute` | O(length), one allocation |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `KeyEncodingInvalidInputError` or `KeyEncodingParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `KeyEncodingInvalidInputError`
`INVALID_KEY_VALUE` `TRUNCATED_KEY` `INVALID_ESCAPE_SEQUENCE` `UNKNOWN_PART_TAG` `INVALID_UTF8` `NON_CANONICAL_FLOAT64`
* `KeyEncodingParseError`
`INVALID_OFFSET` `TRAILING_BYTES`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| persist a whole data structure and read it back later | the structure package's serialize function, over knotkit/wire |
| fingerprint or shard keys where only equality matters, not order | [`knotkit/hash`](/modules/hash/) |
| sort strings by human language rules, case-insensitively, or with accents folded | Intl.Collator |
| keep keys in comparator order in memory and query rank or ranges | [`knotkit/ordered-map`](/modules/ordered-map/) |
| encode arbitrary nested JSON values or schema-evolving records | a general serializer such as JSON, CBOR, or MessagePack, which does not preserve order |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/key-encoding/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/key-encoding/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/key-encodingCopy prompt
```
Use knotkit/key-encoding for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/key-encoding'.
Exports:
- `encodeKeyTuple` → `Uint8Array`: Composite key over bytes, string, 32- and 64-bit integer, and float64 parts, each ascending or descending, ordered part by part under compareBytes with a prefix tuple first.
- `decodeKeyTuple` → `readonly KeyTuplePart[]`: Parts of an encodeKeyTuple key, each with an explicit direction; accepts exactly the bytes encodeKeyTuple writes.
- `compareBytes` → `-1 | 0 | 1`: Unsigned lexicographic order over Uint8Array keys, a proper prefix first; an Order for sorting and comparator-based structures. Does not validate its arguments.
- `commonPrefixLength` → `number`: Count of leading bytes two keys share, from 0 through the shorter length. Does not validate its arguments.
- `bytesPrefixEnd` → `Uint8Array | undefined`: Smallest key greater than every key that starts with a prefix, the exclusive end of a prefix scan; undefined when the prefix is empty or all 0xff.
- `invertKeyBytes` → `Uint8Array`: Bitwise complement of every byte as a new array, reversing the order of keys of one length; a variable-length descending field needs encodeDescendingBytesKey.
Pick the layout by these rules:
- `encodeBytesKey` (kind 'bytes') when the field is a Uint8Array whose keys must sort by the raw bytes, with a byte string sorting before every longer string it prefixes
- `encodeStringKey` (kind 'string') when the field is a JavaScript string without unpaired surrogates and Unicode code point order is the order the caller needs
- `encodeUint32Key` (kind 'uint32') when the field is an integer in 0 .. 2^32 - 1
- `encodeInt32Key` (kind 'int32') when the field is an integer in -2^31 .. 2^31 - 1 that can be negative
- `encodeUint64Key` (kind 'uint64') when the field is a bigint in 0n .. 2n ** 64n - 1n, such as a sequence number or a 64-bit id
- `encodeInt64Key` (kind 'int64') when the field is a bigint in -(2n ** 63n) .. 2n ** 63n - 1n that can be negative
- `encodeFloat64Key` (kind 'float64') when the field is a non-NaN number that is fractional or beyond the safe integers, and -0 and 0 may share one key
Use something else when:
- persist a whole data structure and read it back later → the structure package's serialize function, over knotkit/wire
- fingerprint or shard keys where only equality matters, not order → knotkit/hash
- sort strings by human language rules, case-insensitively, or with accents folded → Intl.Collator
- keep keys in comparator order in memory and query rank or ranges → knotkit/ordered-map
- encode arbitrary nested JSON values or schema-evolving records → a general serializer such as JSON, CBOR, or MessagePack, which does not preserve order
Errors are KeyEncodingInvalidInputError or KeyEncodingParseError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/key-encoding.md
Types: node_modules/knotkit/key-encoding/ and https://knotkit.jkomyno.dev/reference/knotkit/key-encoding/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/key-encoding/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/key-encoding/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/key-encoding/knotkit.capability.json)suggest a change to the source record
# knotkit/ordered-map
> Stores keys in comparator order with insertion, deletion, rank, selection, ceiling, floor, and range scans in either direction, as a B-tree or an indexed skip list
## Use
[Section titled “Use”](#use)
```ts
import { bTreeOrderedMap } from 'knotkit/ordered-map'
const scores = bTreeOrderedMap((a, b) => a - b)
scores.set(30, 'Ada')
scores.set(10, 'Lin')
scores.set(20, 'Sam')
scores.at(1) // [20, 'Sam']
scores.rank(25) // 2
scores.ceiling(25) // [30, 'Ada']
scores.floor(25) // [20, 'Sam']
Array.from(scores.entries(15)) // [[20, 'Sam'], [30, 'Ada']]
Array.from(scores.entriesReverse()) // [[30, 'Ada'], [20, 'Sam'], [10, 'Lin']]
```
ordered-map.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* read the k-th smallest key while keys enter and leave
* count keys at or below a bound
* find the nearest stored key at or above, or at or below, a probe
* iterate key-value entries in a sorted range, from a start key onward, or in descending order
* buffer sorted writes in memory before flushing them in key order, as an LSM MemTable does
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `bTreeOrderedMap`kind `b-tree` | keys change between point, rank, selection or range queries, a comparator defines key equality, and the layout needs no injected random source | worst-case O(log n) per operation; an insertion or deletion shifts up to 64 entries within one leaf |
| `indexedSkipListOrderedMap`kind `indexed-skip-list` | the layout must draw its shape from an injected RandomSource, such as replaying a skip list recorded under a known seed | one node, forward link and span per tower level per entry; worst-case linear search |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/ordered-map/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
Largest map2,04811Seed4242Reset
* For each size, 128 seeded bounds count the keys at or below the bound.
* At 2,048 keys, average comparisons per query: 21.2 indexed, 992.1 for a sequential scan.
* Use the indexed map for rank, positional reads, and ordered walks over changing keys.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/ordered-map/demo.ts) against `knotkit/ordered-map` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| -------------------------------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------- |
| [`bTreeOrderedMap`](/reference/knotkit/ordered-map/functions/btreeorderedmap/) | `OrderedMap` | B+ tree with 64-entry linked leaves and 64-child branches that count the entries under each child. |
| [`indexedSkipListOrderedMap`](/reference/knotkit/ordered-map/functions/indexedskiplistorderedmap/) | `OrderedMap` | Comparator-keyed skip list with a span on each forward link and a predecessor link on the base level. |
Cost per member. Open a row for every operation.
`bTreeOrderedMap` 11 members
| Member | Cost |
| ---------------- | ------------------------------- |
| `set` | O(log n) |
| `get` | O(log n) |
| `has` | O(log n) |
| `delete` | O(log n) |
| `at` | O(log n) |
| `rank` | O(log n) |
| `ceiling` | O(log n) |
| `floor` | O(log n) |
| `entries` | O(n) full, O(log n + k) bounded |
| `entriesReverse` | O(n) full, O(log n + k) bounded |
| `size` | O(1) |
`indexedSkipListOrderedMap` 11 members
| Member | Cost |
| ---------------- | ---------------------------------------- |
| `set` | expected O(log n) |
| `get` | expected O(log n) |
| `has` | expected O(log n) |
| `delete` | expected O(log n) |
| `at` | expected O(log n) |
| `rank` | expected O(log n) |
| `ceiling` | expected O(log n) |
| `floor` | expected O(log n) |
| `entries` | O(n) full, expected O(log n + k) bounded |
| `entriesReverse` | O(n) full, expected O(log n + k) bounded |
| `size` | O(1) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| --------------------------------------------------------------- | -------------- | -------------------------------- |
| key order | `Order` | [`knotkit/heap`](/modules/heap/) |
| tower heights for indexed-skip-list (defaults to splitmix32(0)) | `RandomSource` | [`knotkit/prng`](/modules/prng/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `OrderedMapInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_INDEX` `INVALID_SOURCE_VALUE` `MODIFIED_DURING_ITERATION`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------- | ------------------------------------------------ |
| only keyed lookup with identity equality | Map |
| rank and selection over bounded unsigned integer IDs without payloads | [`knotkit/bitset`](/modules/bitset/) |
| only the smallest or largest element of a changing queue | [`knotkit/heap`](/modules/heap/) |
| an immutable sorted block of byte-keyed entries with seeks | [`knotkit/sorted-block`](/modules/sorted-block/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/ordered-map/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/ordered-map/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Read keys by rank](/benchmarks/#ordered-map).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/ordered-mapCopy prompt
```
Use knotkit/ordered-map for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/ordered-map'.
Exports:
- `bTreeOrderedMap` → `OrderedMap`: B+ tree with 64-entry linked leaves and 64-child branches that count the entries under each child.
- `indexedSkipListOrderedMap` → `OrderedMap`: Comparator-keyed skip list with a span on each forward link and a predecessor link on the base level.
Pick the layout by these rules:
- `bTreeOrderedMap` (kind 'b-tree') when keys change between point, rank, selection or range queries, a comparator defines key equality, and the layout needs no injected random source
- `indexedSkipListOrderedMap` (kind 'indexed-skip-list') when the layout must draw its shape from an injected RandomSource, such as replaying a skip list recorded under a known seed
Inputs and their sources:
- key order: `Order` from `knotkit/heap`
- tower heights for indexed-skip-list (defaults to splitmix32(0)): `RandomSource` from `knotkit/prng`
Use something else when:
- only keyed lookup with identity equality → Map
- rank and selection over bounded unsigned integer IDs without payloads → knotkit/bitset
- only the smallest or largest element of a changing queue → knotkit/heap
- an immutable sorted block of byte-keyed entries with seeks → knotkit/sorted-block
Errors are OrderedMapInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/ordered-map.md
Types: node_modules/knotkit/ordered-map/ and https://knotkit.jkomyno.dev/reference/knotkit/ordered-map/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/ordered-map/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/ordered-map/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/ordered-map/knotkit.capability.json)suggest a change to the source record
# knotkit/prefix-index
> Enumerates a bounded number of distinct strings that start with a prefix in UTF-16 order
## Use
[Section titled “Use”](#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']
```
prefix-index.ts●
ResetEditRun
```
```
```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
[Section titled “What it solves”](#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
[Section titled “Worked example”](#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
[Section titled “API”](#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
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| -------------------- | ------------------ | ------------ |
| string keys to index | `Iterable` | `the caller` |
## Errors
[Section titled “Errors”](#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
[Section titled “When not to use it”](#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
[Section titled “Performance”](#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
[Section titled “Prompt an agent”](#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` 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
[Section titled “See also”](#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
# knotkit/prng
> Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Use
[Section titled “Use”](#use)
```ts
import { splitmix32, uniformInt } from 'knotkit/prng'
const random = splitmix32(42)
random() // 0.12848330102860928
random() // 0.03353364090435207
uniformInt(random, 6) + 1 // a fair die roll
```
prng.ts●
ResetEditRun
```
```
```ts
import { uniformInt64, xoroshiro128StarStar } from 'knotkit/prng'
const random = xoroshiro128StarStar([1n, 2n])
random.next() // 0x1680n
random.next() // 0x16c3804380n
uniformInt64(random.next, 6n) + 1n // a fair die roll as a bigint
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* replay the same random sequence from a seed in tests, simulations, or procedural generation
* roll an unbiased integer in 1..n without modulo bias
* draw unsigned 64-bit values larger than 2^53 without losing precision or capping the bound
* give parallel workers non-overlapping subsequences of one sequence
* produce the same random values in a browser, in Node.js, and in Bun
## Try it
[Section titled “Try it”](#try-it)
Seed4242Rolls6,0006000Reset
* SplitMix32, seed 42: 6,000 six-sided die rolls.
* Counts for faces 1 to 6: 1038, 992, 962, 1016, 999, 993. Expectation: 1000 each.
* Replaying seed 42 reproduced every count. Counts for seed 43: 1020, 1034, 968, 1012, 1011, 955.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/prng/demo.ts) against `knotkit/prng` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`splitmix32`](/reference/knotkit/prng/functions/splitmix32/) | `RandomSource` | Seeded 32-bit generator; the seed is coerced to a signed 32-bit integer and each call yields a value in \`\[0, 1)\`. |
| [`xoroshiro128StarStar`](/reference/knotkit/prng/functions/xoroshiro128starstar/) | `Xoroshiro128StarStar` | Seeded 128-bit-state generator over unsigned 64-bit \`bigint\` draws, matching xoroshiro128\*\* 1.0; input words are reduced modulo 2^64 and must not both reduce to zero. |
| [`uniformInt`](/reference/knotkit/prng/functions/uniformint/) | `number` | Unbiased integer in \`0..upperExclusive - 1\` from an injected \`RandomSource\`; holds no state but advances the source once per consumed draw, rejected draws included. |
| [`uniformInt64`](/reference/knotkit/prng/functions/uniformint64/) | `bigint` | Unbiased \`bigint\` in \`0..upperExclusive - 1\` from an injected \`RandomSource64\`, with no floating-point step, so bounds above 2^32 stay exact. |
Cost per member. Open a row for every operation.
`splitmix32` 1 members
| Member | Cost |
| ------ | ---- |
| `draw` | O(1) |
`xoroshiro128StarStar` 4 members
| Member | Cost |
| ---------- | --------------------- |
| `kind` | O(1) |
| `next` | O(1) |
| `jump` | 128 state transitions |
| `longJump` | 128 state transitions |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `PrngInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_BOUND` `INVALID_SOURCE_VALUE` `INVALID_STATE`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ---------------------------------------------------------------------- | ------------------------------------------------------ |
| generate tokens, passwords, keys, or nonces an attacker cannot predict | [`uniku`](https://www.npmjs.com/package/uniku) |
| one throwaway random number with no reproducibility requirement | the platform Math.random function |
| shuffle an array or pick a weighted choice | [`knotkit/sampling`](/modules/sampling/) |
| derive a fingerprint or a shard key from bytes or text | [`knotkit/hash`](/modules/hash/) |
| draw from a named distribution | [`knotkit/distribution`](/modules/distribution/) |
| test whether draws fit a distribution | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/prng/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/prng/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/prngCopy prompt
```
Use knotkit/prng for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/prng'.
Exports:
- `splitmix32` → `RandomSource`: Seeded 32-bit generator; the seed is coerced to a signed 32-bit integer and each call yields a value in `[0, 1)`.
- `xoroshiro128StarStar` → `Xoroshiro128StarStar`: Seeded 128-bit-state generator over unsigned 64-bit `bigint` draws, matching xoroshiro128** 1.0; input words are reduced modulo 2^64 and must not both reduce to zero.
- `uniformInt` → `number`: Unbiased integer in `0..upperExclusive - 1` from an injected `RandomSource`; holds no state but advances the source once per consumed draw, rejected draws included.
- `uniformInt64` → `bigint`: Unbiased `bigint` in `0..upperExclusive - 1` from an injected `RandomSource64`, with no floating-point step, so bounds above 2^32 stay exact.
Use something else when:
- generate tokens, passwords, keys, or nonces an attacker cannot predict → uniku (https://www.npmjs.com/package/uniku)
- one throwaway random number with no reproducibility requirement → the platform Math.random function
- shuffle an array or pick a weighted choice → knotkit/sampling
- derive a fingerprint or a shard key from bytes or text → knotkit/hash
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test
Errors are PrngInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/prng.md
Types: node_modules/knotkit/prng/ and https://knotkit.jkomyno.dev/reference/knotkit/prng/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/prng/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/prng/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/prng/knotkit.capability.json)suggest a change to the source record
# knotkit/rate-limit
> Limits each client's request weight by a fixed window, a sliding window, or a token bucket, returning the least whole millisecond a denial must wait
## Use
[Section titled “Use”](#use)
```ts
import { fixedWindowRateLimiter } from 'knotkit/rate-limit'
const meter = fixedWindowRateLimiter({
capacity: 2,
windowDuration: 1_000,
clock: () => 582,
})
meter.take(1) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 418 }
```
rate-limit.ts●
ResetEditRun
```
```
```ts
import { keyedRateLimitTable, tokenBucketRateLimiter } from 'knotkit/rate-limit'
const limits = keyedRateLimitTable({
maxKeyCount: 100_000,
whenFull: 'refuse',
clock: () => Date.now(),
meter: (clock) => tokenBucketRateLimiter({ capacity: 20, windowDuration: 1_000, refillAmount: 10, clock }),
})
limits.take('client-7', 1) // { outcome: 'allowed', untracked: false }
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* limit one client's request weight and tell it the least whole millisecond to wait before retrying
* limit many clients without letting the per-client table grow with every client ever seen
* choose a rate-limit algorithm by the most weight it admits in a trailing window rather than by its name
* combine two limits for one client into one meter a keyed table accepts like a built-in kind
* prove a limiter's worst case and its retry boundary by replaying the same arrival schedules
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `fixedWindowRateLimiter`kind `fixed-window` | the reset has to land on a clock face every client can predict, and up to twice the capacity inside one trailing window is acceptable; the boundary-burst schedule reaches exactly 2 x capacity | one window index and one counter per key; O(1) per decision |
| `slidingWindowLogRateLimiter`kind `sliding-window-log` | no trailing window of windowDuration may admit more than capacity, and capacity buffered instants per key fit the memory budget; the boundary-burst schedule reaches exactly capacity in one trailing window | one instant and one weight per admitted unit, at most capacity of them; O(k) amortised per decision |
| `slidingWindowCounterRateLimiter`kind `sliding-window-counter` | two counters per key fit the memory budget, and capacity plus the previous window's decayed remainder is acceptable; the end-of-previous-window schedule reaches 19 against a capacity of 10 | two counters and one window index per key; O(1) per decision |
| `tokenBucketRateLimiter`kind `token-bucket` | the contract is a sustained rate rather than a calendar window, and capacity plus what refills during a trailing window is acceptable; the end-of-previous-window schedule spends its capacity at once and then admits exactly refillAmount in the next window | one arrival time per key, held as two integers; O(1) per decision |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
Capacity88Reset
* On the boundary-burst schedule with a capacity of 8, the four kinds admit 16 / 8 / 8 / 8 units.
* The most any one trailing window holds is 16 (fixed-window, bound 16), 8 (sliding-window-log, bound 8), 8 (sliding-window-counter, bound up to 16), 8 (token-bucket, bound up to 16).
* fixed-window denies it for 1000 ms, exactly: a take there succeeds and one millisecond earlier fails.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/demo.ts) against `knotkit/rate-limit` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| [`fixedWindowRateLimiter`](/reference/knotkit/rate-limit/functions/fixedwindowratelimiter/) | `RateMeter` | Anchors every key to one clock grid and admits until the current window's capacity is spent. |
| [`slidingWindowLogRateLimiter`](/reference/knotkit/rate-limit/functions/slidingwindowlogratelimiter/) | `RateMeter` | Keeps the instant and weight of every request still inside the trailing window, so its decisions and retry times are exact. |
| [`slidingWindowCounterRateLimiter`](/reference/knotkit/rate-limit/functions/slidingwindowcounterratelimiter/) | `RateMeter` | Estimates the trailing window from the current and previous anchored windows, weighting the previous one by how much of it has elapsed. |
| [`tokenBucketRateLimiter`](/reference/knotkit/rate-limit/functions/tokenbucketratelimiter/) | `RateMeter` | Refills continuously at refillAmount per windowDuration, carrying the bucket as one exact arrival time rather than a fractional token count. |
| [`keyedRateLimitTable`](/reference/knotkit/rate-limit/functions/keyedratelimittable/) | `KeyedRateLimitTable` | Holds one caller-built meter per key under a key bound, forgetting a key only once its meter is fresh. |
Cost per member. Open a row for every operation.
`fixedWindowRateLimiter` 3 members
| Member | Cost |
| --------- | ---- |
| `take` | O(1) |
| `peek` | O(1) |
| `freshAt` | O(1) |
`slidingWindowLogRateLimiter` 3 members
| Member | Cost |
| --------- | ---------------------------------------------------- |
| `take` | O(k) amortised, k entries pruned plus the retry scan |
| `peek` | O(k) amortised |
| `freshAt` | O(1) |
`slidingWindowCounterRateLimiter` 3 members
| Member | Cost |
| --------- | ---- |
| `take` | O(1) |
| `peek` | O(1) |
| `freshAt` | O(1) |
`tokenBucketRateLimiter` 3 members
| Member | Cost |
| --------- | ---- |
| `take` | O(1) |
| `peek` | O(1) |
| `freshAt` | O(1) |
`keyedRateLimitTable` 3 members
| Member | Cost |
| ------ | ----------------- |
| `take` | O(log n) expected |
| `peek` | O(log n) expected |
| `size` | O(1) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ----------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------- |
| time source every meter reads; nothing in the module reads the time on its own | `Clock` | [`knotkit/cache`](/modules/cache/) |
| the meter a keyed table builds for each key, which is how a caller supplies an algorithm of their own | `RateMeterFactory` | [`knotkit/rate-limit`](/modules/rate-limit/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `RateLimitInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_CAPACITY` `INVALID_WINDOW_DURATION` `INVALID_REFILL_AMOUNT` `INVALID_WEIGHT` `INVALID_MAX_KEY_COUNT` `INVALID_WHEN_FULL` `INVALID_CLOCK_READING` `PARAMETERS_TOO_LARGE`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| RateLimit or Retry-After response headers, or middleware for one server framework | the server's own response layer, fed by the decision's retryAfter |
| a limit shared across processes or kept outside memory | a store with its own atomic increment and expiry, such as Redis, behind a caller-supplied meter |
| delaying a request until it fits | a queue or a scheduler in front of the request handler |
| bounding how many requests are in flight at once | a concurrency semaphore in the server |
| a decision that survives the process, as meter state on disk | a caller-supplied meter over a durable store, which the keyed table accepts |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/rate-limit/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/rate-limit/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/rate-limitCopy prompt
```
Use knotkit/rate-limit for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/rate-limit'.
Exports:
- `fixedWindowRateLimiter` → `RateMeter`: Anchors every key to one clock grid and admits until the current window's capacity is spent.
- `slidingWindowLogRateLimiter` → `RateMeter`: Keeps the instant and weight of every request still inside the trailing window, so its decisions and retry times are exact.
- `slidingWindowCounterRateLimiter` → `RateMeter`: Estimates the trailing window from the current and previous anchored windows, weighting the previous one by how much of it has elapsed.
- `tokenBucketRateLimiter` → `RateMeter`: Refills continuously at refillAmount per windowDuration, carrying the bucket as one exact arrival time rather than a fractional token count.
- `keyedRateLimitTable` → `KeyedRateLimitTable`: Holds one caller-built meter per key under a key bound, forgetting a key only once its meter is fresh.
Pick the layout by these rules:
- `fixedWindowRateLimiter` (kind 'fixed-window') when the reset has to land on a clock face every client can predict, and up to twice the capacity inside one trailing window is acceptable; the boundary-burst schedule reaches exactly 2 x capacity
- `slidingWindowLogRateLimiter` (kind 'sliding-window-log') when no trailing window of windowDuration may admit more than capacity, and capacity buffered instants per key fit the memory budget; the boundary-burst schedule reaches exactly capacity in one trailing window
- `slidingWindowCounterRateLimiter` (kind 'sliding-window-counter') when two counters per key fit the memory budget, and capacity plus the previous window's decayed remainder is acceptable; the end-of-previous-window schedule reaches 19 against a capacity of 10
- `tokenBucketRateLimiter` (kind 'token-bucket') when the contract is a sustained rate rather than a calendar window, and capacity plus what refills during a trailing window is acceptable; the end-of-previous-window schedule spends its capacity at once and then admits exactly refillAmount in the next window
Inputs and their sources:
- time source every meter reads; nothing in the module reads the time on its own: `Clock` from `knotkit/cache`
- the meter a keyed table builds for each key, which is how a caller supplies an algorithm of their own: `RateMeterFactory` from `knotkit/rate-limit`
Use something else when:
- RateLimit or Retry-After response headers, or middleware for one server framework → the server's own response layer, fed by the decision's retryAfter
- a limit shared across processes or kept outside memory → a store with its own atomic increment and expiry, such as Redis, behind a caller-supplied meter
- delaying a request until it fits → a queue or a scheduler in front of the request handler
- bounding how many requests are in flight at once → a concurrency semaphore in the server
- a decision that survives the process, as meter state on disk → a caller-supplied meter over a durable store, which the keyed table accepts
Errors are RateLimitInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/rate-limit.md
Types: node_modules/knotkit/rate-limit/ and https://knotkit.jkomyno.dev/reference/knotkit/rate-limit/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/rate-limit/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/rate-limit/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/rate-limit/knotkit.capability.json)suggest a change to the source record
# knotkit/sampling
> Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
## Use
[Section titled “Use”](#use)
```ts
import { splitmix32 } from 'knotkit/prng'
import { sampleIndices, shuffled, weightedChoice } from 'knotkit/sampling'
const random = splitmix32(42)
sampleIndices(random, 10, 3) // three distinct indices in ascending order
shuffled(random, ['a', 'b', 'c']) // a new array; the input is untouched
weightedChoice(random, [1, 2, 0]) // index 0 or 1; never 2
```
sampling.ts●
ResetEditRun
```
```
```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'
const sampler = reservoirSampler(splitmix32(42), 3)
sampler.addAll([1, 2, 3, 4, 5])
sampler.snapshot() // three of the five values, each retained with probability 3/5
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* pick k distinct items from a population or an index range without shuffling the whole population
* shuffle a copy of a list reproducibly, so a rerun from the same seed yields the same order
* pick one item in proportion to its weight, or k items in proportion to their weights without replacement
* keep a bounded uniform sample of a stream whose length is not known in advance
* pick two distinct items, optionally at least a minimum number of positions apart
* replay a simulation or a generated test fixture exactly from a recorded seed
## Try it
[Section titled “Try it”](#try-it)
Seed4242Draws4,0004000Reset
* 4,000 weighted choices with seed 42 and weights \[1, 2, 7, 0].
* Observed picks per item: 397, 828, 2775, 0.
* The zero-weight item is ineligible. Each call draws one item independently.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/sampling/demo.ts) against `knotkit/sampling` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ----------------------------------------------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`sampleIndices`](/reference/knotkit/sampling/functions/sampleindices/) | `readonly number[]` | Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation. |
| [`samplePair`](/reference/knotkit/sampling/functions/samplepair/) | `readonly [number, number]` | Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space. |
| [`sampleConstrainedPair`](/reference/knotkit/sampling/functions/sampleconstrainedpair/) | `readonly [number, number]` | Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank. |
| [`shuffled`](/reference/knotkit/sampling/functions/shuffled/) | `readonly T[]` | Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched. |
| [`weightedChoice`](/reference/knotkit/sampling/functions/weightedchoice/) | `number` | One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space. |
| [`weightedSample`](/reference/knotkit/sampling/functions/weightedsample/) | `readonly number[]` | k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space. |
| [`weightedSampleFromLogWeights`](/reference/knotkit/sampling/functions/weightedsamplefromlogweights/) | `readonly number[]` | The same k indices without replacement taken from log-weights directly, skipping \`Math.exp\`, so a log-weight of \`-800\` stays eligible and \`-Infinity\` marks an entry as unreachable; O(n log k) time and O(k) space. |
| [`reservoirSampler`](/reference/knotkit/sampling/functions/reservoirsampler/) | `ReservoirSampler` | Vitter's Algorithm R over a stream: fills the first \`capacity\` values, then retains the n-th with probability \`capacity / n\`. \`add\` throws \`STREAM_LIMIT_EXCEEDED\` once 2^32 values have been observed. |
Cost per member. Open a row for every operation.
`reservoirSampler` 4 members
| Member | Cost |
| ----------- | -------------- |
| `add` | O(1) amortized |
| `addAll` | O(1) per value |
| `seenCount` | O(1) |
| `snapshot` | O(capacity) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ------------------------------------------------------------------------------------------------------------ | -------------- | -------------------------------- |
| randomness, consumed once per draw and never created or owned; the same source state replays the same sample | `RandomSource` | [`knotkit/prng`](/modules/prng/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `SamplingInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `SamplingInvalidInputError`
`INVALID_POPULATION_SIZE` `INVALID_SAMPLE_SIZE` `INVALID_RANGE` `INVALID_GAP` `INVALID_WEIGHT` `INVALID_LOG_WEIGHT` `ZERO_TOTAL_WEIGHT` `INSUFFICIENT_POSITIVE_WEIGHT` `INVALID_CAPACITY`
* `Other`
`STREAM_LIMIT_EXCEEDED`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| -------------------------------------------------------------------------- | ------------------------------------------------------ |
| a seeded random source of your own, or the sequence the draws come from | [`knotkit/prng`](/modules/prng/) |
| randomness an attacker must not be able to predict | crypto.getRandomValues |
| sample with replacement | one weighted draw per item over a shared random source |
| keep the drawn items ordered, or evict the weakest of them as more arrive | [`knotkit/heap`](/modules/heap/) |
| estimate how many distinct values a stream held, or how often one occurred | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| draw from a named distribution | [`knotkit/distribution`](/modules/distribution/) |
| test whether draws fit a distribution | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/sampling/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/sampling/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/samplingCopy prompt
```
Use knotkit/sampling for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sampling'.
Exports:
- `sampleIndices` → `readonly number[]`: Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.
- `samplePair` → `readonly [number, number]`: Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.
- `sampleConstrainedPair` → `readonly [number, number]`: Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
- `shuffled` → `readonly T[]`: Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.
- `weightedChoice` → `number`: One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
- `weightedSample` → `readonly number[]`: k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
- `weightedSampleFromLogWeights` → `readonly number[]`: The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
- `reservoirSampler` → `ReservoirSampler`: Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.
Inputs and their sources:
- randomness, consumed once per draw and never created or owned; the same source state replays the same sample: `RandomSource` from `knotkit/prng`
Use something else when:
- a seeded random source of your own, or the sequence the draws come from → knotkit/prng
- randomness an attacker must not be able to predict → crypto.getRandomValues
- sample with replacement → one weighted draw per item over a shared random source
- keep the drawn items ordered, or evict the weakest of them as more arrive → knotkit/heap
- estimate how many distinct values a stream held, or how often one occurred → knotkit/scalar-sketch
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test
Errors are SamplingInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/sampling.md
Types: node_modules/knotkit/sampling/ and https://knotkit.jkomyno.dev/reference/knotkit/sampling/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/sampling/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/sampling/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/sampling/knotkit.capability.json)suggest a change to the source record
# knotkit/scalar-sketch
> Provides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains
## Use
[Section titled “Use”](#use)
```ts
import { stringSplitBlockBloomFilter } from 'knotkit/scalar-sketch'
const filter = stringSplitBlockBloomFilter({
expectedEntries: 10_000,
targetFalsePositiveProbability: 0.01,
seed: 7n,
})
filter.update('alpha')
filter.mightContain('alpha') // true — no false negatives
filter.mightContain('omega') // almost always false
filter.blockCount // 512 — a power of two, chosen by the model
```
scalar-sketch.ts●
ResetEditRun
```
```
```ts
import { stringSplitBlockBloomFilter } from 'knotkit/scalar-sketch'
import { deserializeScalarSketch, serializeScalarSketch } from 'knotkit/scalar-sketch/wire'
const options = { expectedEntries: 10_000, seed: 7n }
const shard = stringSplitBlockBloomFilter(options)
const other = stringSplitBlockBloomFilter(options)
shard.update('alpha')
other.update('beta')
shard.merge(other) // union in place; `other` is untouched
const smaller = shard.reduce(shard.blockCount / 2) // half the state, a higher error model
const restored = deserializeScalarSketch(serializeScalarSketch(smaller))
if (restored.kind === 'split-block-bloom-filter' && restored.scalarKind === 'string') {
restored.mightContain('alpha') // true
}
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* count distinct visitors without storing every visitor
* check whether an id or URL was already processed, with a small false-positive rate and no false negatives
* find the heavy hitters of a stream without keeping a counter per key
* estimate how much two large sets overlap without holding both of them
* answer those questions per partition and merge the answers afterwards
* keep the answer in a fixed-size summary that is serialized now and queried later
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `stringSplitBlockBloomFilter`kind `split-block-bloom-filter` | the question is membership, a rare false positive is acceptable, and \`expectedEntries\` is known before the first update; the \`string\`, \`bytes\`, \`uint32\`, and \`uint64\` factories are this one layout over four value domains | \`blockCount\` 256-bit blocks, a power of two, 16 KiB at \`expectedEntries\` 10,000 and a 0.01 target rate; one block touched per update |
| `stringHyperLogLog`kind `hyperloglog` | the question is how many distinct values there are, the reported \`relativeStandardError\` of \`1.04 / sqrt(registerCount)\` is acceptable, and the values themselves need not be retained; the four domain factories differ only in how a value is hashed | one byte per register over \`2 \*\* precision\` registers, 16 KiB at the default precision 14 for a 0.8% relative standard error |
| `stringCountMinSketch`kind `count-min-sketch` | the question is how often each value occurred, an overestimate is acceptable, and the reported \`epsilon\` and \`confidence\` bounds fit the caller's tolerance; the four domain factories differ only in how a value is hashed | \`width \* depth\` 32-bit counters, 4096 columns and 5 rows at the default \`epsilon\` 0.001 and \`confidence\` 0.99, 80 KiB |
| `stringMinHash`kind `minhash` | the question is how much two sets overlap, as an estimated Jaccard index, one signature per set fits where the sets do not, and \`maximumStandardError\` of \`1 / (2 \* sqrt(signatureSize))\` is acceptable | \`signatureSize\` 64-bit coordinate minima, 1 KiB at the default 128 coordinates, and one digest per coordinate per value |
| `string*`kind `string` | values are JavaScript strings and the caller accepts O(length) hashing per operation, which every string-domain sketch pays on \`update\` and on the query that takes a value | one XXH64 digest over the UTF-8 bytes, so time and cache pressure scale with string length rather than with state size |
| `bytes*`kind `bytes` | values are \`Uint8Array\` byte sequences, such as digests or serialized records, and hashing those exact bytes is what the caller wants | one XXH64 digest over the raw bytes, O(length) per operation |
| `uint32*`kind `uint32` | values are integers in \`0..2^32 - 1\`, so every operation hashes in O(1) with no encoding step | one XXH64 digest of four bytes per operation, independent of state size |
| `uint64*`kind `uint64` | values are \`bigint\`s in \`0n..2^64 - 1n\`, so every operation hashes in O(1) and the full 64-bit domain survives | one XXH64 digest of eight bytes per operation, independent of state size |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/README.md#performance)
## Try it
[Section titled “Try it”](#try-it)
Seed77Reset
* Membership can return a false positive. The rate rises when a filter fills past its design load.
* Choose the sketch by the question: membership, distinct count, frequency, or similarity.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/demo.ts) against `knotkit/scalar-sketch` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| -------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [`stringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/stringsplitblockbloomfilter/) | `StringSplitBlockBloomFilter` | String membership with no false negatives. \`expectedEntries\` is required; the block count rounds up to a power of two. |
| [`bytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/bytessplitblockbloomfilter/) | `BytesSplitBlockBloomFilter` | Membership over \`Uint8Array\` values, hashing the raw bytes. |
| [`uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/uint32splitblockbloomfilter/) | `Uint32SplitBlockBloomFilter` | Membership over integers in \`0..2^32 - 1\`, hashed without an encoding step. |
| [`uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/uint64splitblockbloomfilter/) | `Uint64SplitBlockBloomFilter` | Membership over \`bigint\` values in \`0n..2^64 - 1n\`. |
| [`stringHyperLogLog`](/reference/knotkit/scalar-sketch/functions/stringhyperloglog/) | `StringHyperLogLog` | Distinct-count estimate over strings, by Ertl's improved raw estimator over one-byte registers. |
| [`bytesHyperLogLog`](/reference/knotkit/scalar-sketch/functions/byteshyperloglog/) | `BytesHyperLogLog` | Distinct-count estimate over \`Uint8Array\` values; \`precision\` defaults to 14 and may be reduced exactly. |
| [`uint32HyperLogLog`](/reference/knotkit/scalar-sketch/functions/uint32hyperloglog/) | `Uint32HyperLogLog` | Distinct-count estimate over integers in \`0..2^32 - 1\`. |
| [`uint64HyperLogLog`](/reference/knotkit/scalar-sketch/functions/uint64hyperloglog/) | `Uint64HyperLogLog` | Distinct-count estimate over \`bigint\` values in \`0n..2^64 - 1n\`. |
| [`stringCountMinSketch`](/reference/knotkit/scalar-sketch/functions/stringcountminsketch/) | `StringCountMinSketch` | Per-value frequency over strings; the minimum counter across rows never underestimates an accepted stream. |
| [`bytesCountMinSketch`](/reference/knotkit/scalar-sketch/functions/bytescountminsketch/) | `BytesCountMinSketch` | Per-value frequency over \`Uint8Array\` values; weights are unsigned 32-bit integers and zero is a no-op. |
| [`uint32CountMinSketch`](/reference/knotkit/scalar-sketch/functions/uint32countminsketch/) | `Uint32CountMinSketch` | Per-value frequency over integers in \`0..2^32 - 1\`. |
| [`uint64CountMinSketch`](/reference/knotkit/scalar-sketch/functions/uint64countminsketch/) | `Uint64CountMinSketch` | Per-value frequency over \`bigint\` values in \`0n..2^64 - 1n\`. |
| [`stringMinHash`](/reference/knotkit/scalar-sketch/functions/stringminhash/) | `StringMinHash` | Jaccard-estimate signature over strings: \`signatureSize\` ordered coordinate minima, prefix-stable under \`reduce\`. |
| [`bytesMinHash`](/reference/knotkit/scalar-sketch/functions/bytesminhash/) | `BytesMinHash` | Jaccard-estimate signature over \`Uint8Array\` values; \`signatureSize\` defaults to 128. |
| [`uint32MinHash`](/reference/knotkit/scalar-sketch/functions/uint32minhash/) | `Uint32MinHash` | Jaccard-estimate signature over integers in \`0..2^32 - 1\`. |
| [`uint64MinHash`](/reference/knotkit/scalar-sketch/functions/uint64minhash/) | `Uint64MinHash` | Jaccard-estimate signature over \`bigint\` values in \`0n..2^64 - 1n\`. |
Cost per member. Open a row for every operation.
`stringSplitBlockBloomFilter` 4 members
| Member | Cost |
| -------------- | ------------- |
| `update` | O(length) |
| `mightContain` | O(length) |
| `merge` | O(blockCount) |
| `reduce` | O(blockCount) |
`bytesSplitBlockBloomFilter` 4 members
| Member | Cost |
| -------------- | ------------- |
| `update` | O(length) |
| `mightContain` | O(length) |
| `merge` | O(blockCount) |
| `reduce` | O(blockCount) |
`uint32SplitBlockBloomFilter` 4 members
| Member | Cost |
| -------------- | ------------- |
| `update` | O(1) |
| `mightContain` | O(1) |
| `merge` | O(blockCount) |
| `reduce` | O(blockCount) |
`uint64SplitBlockBloomFilter` 4 members
| Member | Cost |
| -------------- | ------------- |
| `update` | O(1) |
| `mightContain` | O(1) |
| `merge` | O(blockCount) |
| `reduce` | O(blockCount) |
`stringHyperLogLog` 4 members
| Member | Cost |
| ---------- | ------------------------------------------------------- |
| `update` | O(length) |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge` | O(registerCount) |
| `reduce` | O(registerCount) |
`bytesHyperLogLog` 4 members
| Member | Cost |
| ---------- | ------------------------------------------------------- |
| `update` | O(length) |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge` | O(registerCount) |
| `reduce` | O(registerCount) |
`uint32HyperLogLog` 4 members
| Member | Cost |
| ---------- | ------------------------------------------------------- |
| `update` | O(1) |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge` | O(registerCount) |
| `reduce` | O(registerCount) |
`uint64HyperLogLog` 4 members
| Member | Cost |
| ---------- | ------------------------------------------------------- |
| `update` | O(1) |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge` | O(registerCount) |
| `reduce` | O(registerCount) |
`stringCountMinSketch` 4 members
| Member | Cost |
| ---------- | ------------------ |
| `update` | O(depth \* length) |
| `estimate` | O(depth \* length) |
| `merge` | O(width \* depth) |
| `reduce` | O(width \* depth) |
`bytesCountMinSketch` 4 members
| Member | Cost |
| ---------- | ------------------ |
| `update` | O(depth \* length) |
| `estimate` | O(depth \* length) |
| `merge` | O(width \* depth) |
| `reduce` | O(width \* depth) |
`uint32CountMinSketch` 4 members
| Member | Cost |
| ---------- | ----------------- |
| `update` | O(depth) |
| `estimate` | O(depth) |
| `merge` | O(width \* depth) |
| `reduce` | O(width \* depth) |
`uint64CountMinSketch` 4 members
| Member | Cost |
| ---------- | ----------------- |
| `update` | O(depth) |
| `estimate` | O(depth) |
| `merge` | O(width \* depth) |
| `reduce` | O(width \* depth) |
`stringMinHash` 5 members
| Member | Cost |
| ------------ | -------------------------- |
| `update` | O(signatureSize \* length) |
| `snapshot` | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge` | O(signatureSize) |
| `reduce` | O(signatureSize) |
`bytesMinHash` 5 members
| Member | Cost |
| ------------ | -------------------------- |
| `update` | O(signatureSize \* length) |
| `snapshot` | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge` | O(signatureSize) |
| `reduce` | O(signatureSize) |
`uint32MinHash` 5 members
| Member | Cost |
| ------------ | ---------------- |
| `update` | O(signatureSize) |
| `snapshot` | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge` | O(signatureSize) |
| `reduce` | O(signatureSize) |
`uint64MinHash` 5 members
| Member | Cost |
| ------------ | ---------------- |
| `update` | O(signatureSize) |
| `snapshot` | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge` | O(signatureSize) |
| `reduce` | O(signatureSize) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------------------------------- |
| hash identity, the seeded XXH64 instance that produces every digest and decides whether two sketches may merge | `bigint seed selecting an XXH64 identity` | [`knotkit/hash`](/modules/hash/) |
| seed, defaulting to \`0n\` and folded into merge compatibility; an invalid seed surfaces \`HashInvalidInputError\` from \`knotkit/hash\` | `bigint` | [`knotkit/hash`](/modules/hash/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `ScalarSketchInvalidInputError` or `ScalarSketchParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `ScalarSketchInvalidInputError`
`INVALID_PROBABILITY` `INVALID_DIMENSION` `INVALID_PRECISION` `INVALID_SIGNATURE_SIZE` `STATE_TOO_LARGE`
* `ScalarSketchParseError`
`FOREIGN_STRUCTURE` `WRONG_FAMILY` `INCOMPATIBLE_SKETCH` `INVALID_REDUCTION` `INVALID_WEIGHT` `CAPACITY_EXCEEDED` `COUNTER_OVERFLOW` `INVALID_SHAPE` `INVALID_ENVELOPE` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `UNKNOWN_SCALAR_KIND` `UNSUPPORTED_WIRE_VERSION` `UNSUPPORTED_PRODUCER_VERSION` `UNSUPPORTED_SCHEDULE` `INVALID_STATE`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/scalar-sketch/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeScalarSketch`, `deserializeScalarSketch`, `serializeScalarSketchJson`, `deserializeScalarSketchJson`
* Formats
binary, json
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------- |
| an exact set, where a false positive is unacceptable | Set, Map |
| the exact count of a value, or a count that never exaggerates | Map\ |
| read back the values that were observed | [`knotkit/snapshot-set`](/modules/snapshot-set/) |
| keep a bounded random sample of the stream instead of a summary of it | [`knotkit/sampling`](/modules/sampling/) |
| test membership in a key set that is complete before the first query and never changes, in fewer bytes | [`knotkit/static-filter`](/modules/static-filter/) |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/scalar-sketch/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/scalar-sketch/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/scalar-sketchCopy prompt
```
Use knotkit/scalar-sketch for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/scalar-sketch'.
Exports:
- `stringSplitBlockBloomFilter` → `StringSplitBlockBloomFilter`: String membership with no false negatives. `expectedEntries` is required; the block count rounds up to a power of two.
- `bytesSplitBlockBloomFilter` → `BytesSplitBlockBloomFilter`: Membership over `Uint8Array` values, hashing the raw bytes.
- `uint32SplitBlockBloomFilter` → `Uint32SplitBlockBloomFilter`: Membership over integers in `0..2^32 - 1`, hashed without an encoding step.
- `uint64SplitBlockBloomFilter` → `Uint64SplitBlockBloomFilter`: Membership over `bigint` values in `0n..2^64 - 1n`.
- `stringHyperLogLog` → `StringHyperLogLog`: Distinct-count estimate over strings, by Ertl's improved raw estimator over one-byte registers.
- `bytesHyperLogLog` → `BytesHyperLogLog`: Distinct-count estimate over `Uint8Array` values; `precision` defaults to 14 and may be reduced exactly.
- `uint32HyperLogLog` → `Uint32HyperLogLog`: Distinct-count estimate over integers in `0..2^32 - 1`.
- `uint64HyperLogLog` → `Uint64HyperLogLog`: Distinct-count estimate over `bigint` values in `0n..2^64 - 1n`.
- `stringCountMinSketch` → `StringCountMinSketch`: Per-value frequency over strings; the minimum counter across rows never underestimates an accepted stream.
- `bytesCountMinSketch` → `BytesCountMinSketch`: Per-value frequency over `Uint8Array` values; weights are unsigned 32-bit integers and zero is a no-op.
- `uint32CountMinSketch` → `Uint32CountMinSketch`: Per-value frequency over integers in `0..2^32 - 1`.
- `uint64CountMinSketch` → `Uint64CountMinSketch`: Per-value frequency over `bigint` values in `0n..2^64 - 1n`.
- `stringMinHash` → `StringMinHash`: Jaccard-estimate signature over strings: `signatureSize` ordered coordinate minima, prefix-stable under `reduce`.
- `bytesMinHash` → `BytesMinHash`: Jaccard-estimate signature over `Uint8Array` values; `signatureSize` defaults to 128.
- `uint32MinHash` → `Uint32MinHash`: Jaccard-estimate signature over integers in `0..2^32 - 1`.
- `uint64MinHash` → `Uint64MinHash`: Jaccard-estimate signature over `bigint` values in `0n..2^64 - 1n`.
Pick the layout by these rules:
- `stringSplitBlockBloomFilter` (kind 'split-block-bloom-filter') when the question is membership, a rare false positive is acceptable, and `expectedEntries` is known before the first update; the `string`, `bytes`, `uint32`, and `uint64` factories are this one layout over four value domains
- `stringHyperLogLog` (kind 'hyperloglog') when the question is how many distinct values there are, the reported `relativeStandardError` of `1.04 / sqrt(registerCount)` is acceptable, and the values themselves need not be retained; the four domain factories differ only in how a value is hashed
- `stringCountMinSketch` (kind 'count-min-sketch') when the question is how often each value occurred, an overestimate is acceptable, and the reported `epsilon` and `confidence` bounds fit the caller's tolerance; the four domain factories differ only in how a value is hashed
- `stringMinHash` (kind 'minhash') when the question is how much two sets overlap, as an estimated Jaccard index, one signature per set fits where the sets do not, and `maximumStandardError` of `1 / (2 * sqrt(signatureSize))` is acceptable
- `string*` (kind 'string') when values are JavaScript strings and the caller accepts O(length) hashing per operation, which every string-domain sketch pays on `update` and on the query that takes a value
- `bytes*` (kind 'bytes') when values are `Uint8Array` byte sequences, such as digests or serialized records, and hashing those exact bytes is what the caller wants
- `uint32*` (kind 'uint32') when values are integers in `0..2^32 - 1`, so every operation hashes in O(1) with no encoding step
- `uint64*` (kind 'uint64') when values are `bigint`s in `0n..2^64 - 1n`, so every operation hashes in O(1) and the full 64-bit domain survives
Inputs and their sources:
- hash identity, the seeded XXH64 instance that produces every digest and decides whether two sketches may merge: `bigint seed selecting an XXH64 identity` from `knotkit/hash`
- seed, defaulting to `0n` and folded into merge compatibility; an invalid seed surfaces `HashInvalidInputError` from `knotkit/hash`: `bigint` from `knotkit/hash`
Use something else when:
- an exact set, where a false positive is unacceptable → Set, Map
- the exact count of a value, or a count that never exaggerates → Map
- read back the values that were observed → knotkit/snapshot-set
- keep a bounded random sample of the stream instead of a summary of it → knotkit/sampling
- test membership in a key set that is complete before the first query and never changes, in fewer bytes → knotkit/static-filter
Errors are ScalarSketchInvalidInputError or ScalarSketchParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/scalar-sketch/wire` (serializeScalarSketch, deserializeScalarSketch, serializeScalarSketchJson, deserializeScalarSketchJson).
Full page: https://knotkit.jkomyno.dev/modules/scalar-sketch.md
Types: node_modules/knotkit/scalar-sketch/ and https://knotkit.jkomyno.dev/reference/knotkit/scalar-sketch/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/scalar-sketch/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/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/scalar-sketch/knotkit.capability.json)suggest a change to the source record
# knotkit/snapshot-set
> Keeps every snapshot readable for the lifetime of the set, at O(1) mutation and snapshot cost
## Use
[Section titled “Use”](#use)
```ts
import { snapshotSet } from 'knotkit/snapshot-set'
const set = snapshotSet(['a'])
const s1 = set.createSnapshot()
set.delete('a')
set.has('a') // false
set.hasAt(s1, 'a') // true — the snapshot is unaffected by the later delete
```
snapshot-set.ts●
ResetEditRun
```
```
```ts
const s = snapshotSet()
s.add('a') // true
s.add('a') // false, already present
s.add('b')
s.add('c')
s.delete('b') // true
s.delete('z') // false, never present
s.add('b')
;[...s.values()] // ['a', 'b', 'c'] — 'b' keeps its original position
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* read a set as it was at an earlier point, while it keeps changing
* answer whether a value was present at a given moment, for an audit trail or a change log
* serve MVCC reads: older readers keep their view while a writer mutates
* keep an undo stack over membership, or time-travel debug a collection, without cloning it per step
* report when each value joined and left a live set, as of any snapshot taken earlier
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `snapshotSet`kind `version-chain` | the caller mints snapshots and later mutations must not change any answer derived from an id already minted, and mutation plus snapshot cost must stay O(1) rather than cloning the set per snapshot | one immutable version entry per effective toggle and one Set insert per minted id; \`hasAt\` binary-searches that value's toggles, and \`valuesAt\` pays O(r log h) over every value registered by the snapshot, not just the ones it returns |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/snapshot-set/README.md#performance)
## Worked example
[Section titled “Worked example”](#worked-example)
Set size1287Reset
* Original checkpoint has key 0: true. Current set has key 0: false.
* After 12 checkpoints, full copies write 1536 memberships. The version chain records 24 membership changes.
* The work model counts membership history after initialization.
Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/snapshot-set/demo.ts) against `knotkit/snapshot-set` in your browser; the defaults reproduce the README figure.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ----------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [`snapshotSet`](/reference/knotkit/snapshot-set/functions/snapshotset/) | `SnapshotSet` | Mutable set whose snapshots are O(1) ids over a per-value toggle-version history, so a minted id never changes its answer. |
Cost per member. Open a row for every operation.
`snapshotSet` 8 members
| Member | Cost |
| ---------------- | ------------------------- |
| `size` | O(1) |
| `has` | O(1) average |
| `add` | O(1) amortized |
| `delete` | O(1) average |
| `values` | O(1) per step, O(n) total |
| `createSnapshot` | O(1) |
| `hasAt` | O(log h) |
| `valuesAt` | O(r log h) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ----------------------------------------------------------------------------- | -------------------------------- | -------------------------------- |
| value encoding for a binary artifact, which no artifact carries back | `ElementCodec` | [`knotkit/wire`](/modules/wire/) |
| value validation for a JSON artifact, whose projection carries no value types | `(value: unknown) => value is T` | `the caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `SnapshotSetInvalidInputError` or `SnapshotSetParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `FOREIGN_SNAPSHOT_SET` `SNAPSHOT_ID_NOT_MINTED` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_VALUES` `MISSING_HISTORY` `VALUES_HISTORY_LENGTH_MISMATCH` `INVALID_SNAPSHOTS` `INVALID_VERSION` `INVALID_HISTORY_ENTRY` `EMPTY_HISTORY_ENTRY` `HISTORY_NOT_STRICTLY_INCREASING` `HISTORY_EXCEEDS_VERSION` `HISTORY_ORDER_VIOLATION` `SNAPSHOT_EXCEEDS_VERSION` `DUPLICATE_VALUE` `INVALID_VALUE` `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
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/snapshot-set/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeSnapshotSet`, `deserializeSnapshotSet`, `serializeSnapshotSetJson`, `deserializeSnapshotSetJson`
* Formats
binary, json
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| a plain set with no history | Set |
| keep every version of a keyed value, not just membership | a persistent data-structure library such as immutable.js, or structuredClone per version |
| record which elements belong to the same group, and merge groups | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| reclaim the memory a snapshot holds once nobody reads it | drop the id and rebuild the set from your own change log, because a snapshot lives for the set's lifetime |
| serialize identically-behaving sets to identical bytes | your own canonical projection, because a snapshot-set artifact records the mutation path it took |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/snapshot-set/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/snapshot-set/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#snapshot-set).
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/snapshot-setCopy prompt
```
Use knotkit/snapshot-set for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/snapshot-set'.
Exports:
- `snapshotSet` → `SnapshotSet`: Mutable set whose snapshots are O(1) ids over a per-value toggle-version history, so a minted id never changes its answer.
Pick the layout by these rules:
- `snapshotSet` (kind 'version-chain') when the caller mints snapshots and later mutations must not change any answer derived from an id already minted, and mutation plus snapshot cost must stay O(1) rather than cloning the set per snapshot
Inputs and their sources:
- value encoding for a binary artifact, which no artifact carries back: `ElementCodec` from `knotkit/wire`
- value validation for a JSON artifact, whose projection carries no value types: `(value: unknown) => value is T` from `the caller`
Use something else when:
- a plain set with no history → Set
- keep every version of a keyed value, not just membership → a persistent data-structure library such as immutable.js, or structuredClone per version
- record which elements belong to the same group, and merge groups → knotkit/disjoint-set
- reclaim the memory a snapshot holds once nobody reads it → drop the id and rebuild the set from your own change log, because a snapshot lives for the set's lifetime
- serialize identically-behaving sets to identical bytes → your own canonical projection, because a snapshot-set artifact records the mutation path it took
Errors are SnapshotSetInvalidInputError or SnapshotSetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/snapshot-set/wire` (serializeSnapshotSet, deserializeSnapshotSet, serializeSnapshotSetJson, deserializeSnapshotSetJson).
Full page: https://knotkit.jkomyno.dev/modules/snapshot-set.md
Types: node_modules/knotkit/snapshot-set/ and https://knotkit.jkomyno.dev/reference/knotkit/snapshot-set/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/snapshot-set/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/snapshot-set/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/snapshot-set/knotkit.capability.json)suggest a change to the source record
# knotkit/sorted-block
> Packs byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans
## Use
[Section titled “Use”](#use)
```ts
import { encodeKeyTuple } from 'knotkit/key-encoding'
import { restartPointSortedBlock } from 'knotkit/sorted-block'
const encoder = new TextEncoder()
const key = (user: string, version: bigint): Uint8Array =>
encodeKeyTuple([
{ kind: 'string', value: user },
{ kind: 'uint64', value: version, direction: 'descending' },
])
// Entries must already ascend under compareBytes: here, each user's newest version first.
const block = restartPointSortedBlock(
[
[key('ada', 2n), encoder.encode('engineer')],
[key('ada', 1n), encoder.encode('student')],
[key('grace', 1n), encoder.encode('admiral')],
],
{ restartInterval: 16 },
)
block.size // 3
block.get(key('ada', 1n)) // the bytes of 'student'
block.has(key('ada', 3n)) // false
// A user's key prefix sorts before every one of its versions, so the ceiling is the newest one.
const ada = encodeKeyTuple([{ kind: 'string', value: 'ada' }])
const [, latest] = block.ceiling(ada) ?? []
new TextDecoder().decode(latest) // 'engineer'
// Every entry from user 'ada' up to, not including, user 'grace'.
const grace = encodeKeyTuple([{ kind: 'string', value: 'grace' }])
const versions = [...block.entries(ada, grace)].length // 2
```
sorted-block.ts●
ResetEditRun
```
```
```ts
import { compareBytes } from 'knotkit/key-encoding'
import { restartPointSortedBlock, type SortedBlockEntry } from 'knotkit/sorted-block'
import { mergeSorted } from 'knotkit/sorted-merge'
const key = Uint8Array.of(1)
const newest = restartPointSortedBlock([[key, Uint8Array.of(20)]])
const oldest = restartPointSortedBlock([[key, Uint8Array.of(10)]])
function* firstPerKey(entries: Iterable) {
let previous: Uint8Array | undefined
for (const entry of entries) {
if (previous === undefined || compareBytes(previous, entry[0]) !== 0) {
previous = entry[0]
yield entry
}
}
}
const merged = mergeSorted((a, b) => compareBytes(a[0], b[0]), [newest, oldest])
const compacted = restartPointSortedBlock(firstPerKey(merged))
compacted.get(key) // Uint8Array [20]
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* build the data or index block of a sorted string table from key-value pairs already in key order
* store many sorted Uint8Array keys that share long prefixes in fewer bytes than an array of pairs
* look up, seek to the first key at or above a bound, or scan a key range in a block built once
* persist a sorted run as bytes and reload it with every offset, varint, and key order validated
* trade block size against lookup cost by choosing how often a key is stored whole
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `restartPointSortedBlock`kind `restart-point` | the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built | three varints, the unshared key bytes, and the value per entry, 4 bytes per restart point, and an 8-byte trailer; 385,963 bytes at restartInterval 16 for 10,000 23-byte keys with 32-byte values, 550,000 bytes raw |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/sorted-block/README.md#performance)
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ----------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`restartPointSortedBlock`](/reference/knotkit/sorted-block/functions/restartpointsortedblock/) | `SortedBlock` | Immutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole. |
Cost per member. Open a row for every operation.
`restartPointSortedBlock` 8 members
| Member | Cost |
| ---------- | ---------------------------------------------------------------------------------------- |
| `build` | O(total key and value bytes) |
| `size` | O(1) |
| `firstKey` | O(k) |
| `lastKey` | O(k) |
| `get` | O(k log(n / r) + r k + v), including v returned value bytes |
| `has` | O(k log(n / r) + r k) |
| `ceiling` | O(k log(n / r) + r k + v), including v returned value bytes |
| `entries` | O(k log(n / r) + r k) to start, then O(k + v) per entry including v returned value bytes |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `SortedBlockInvalidInputError` or `SortedBlockParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `SortedBlockInvalidInputError`
`INVALID_RESTART_INTERVAL` `INVALID_ENTRY` `UNSORTED_KEY` `DUPLICATE_KEY` `MAX_CAPACITY_EXCEEDED`
* `SortedBlockParseError`
`INVALID_KEY` `INVALID_RANGE` `FOREIGN_SORTED_BLOCK` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `CORRUPT_BLOCK_PAYLOAD` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/sorted-block/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeSortedBlock`, `deserializeSortedBlock`
* Formats
binary
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| insert, update, or delete keys after the structure is built | [`knotkit/ordered-map`](/modules/ordered-map/) |
| turn integers, strings, or tuples into byte keys whose order matches the values | [`knotkit/key-encoding`](/modules/key-encoding/) |
| merge several sorted runs before building a block (resolve equal keys in the merged stream) | [`knotkit/sorted-merge`](/modules/sorted-merge/) |
| look up keys by exact match only, with no order, seek, or range scan | Map |
| a whole persistent store with writes, compaction, and crash recovery | an embedded key-value store such as SQLite, LevelDB, or RocksDB |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/sorted-block/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/sorted-block/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/sorted-blockCopy prompt
```
Use knotkit/sorted-block for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sorted-block'.
Exports:
- `restartPointSortedBlock` → `SortedBlock`: Immutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole.
Pick the layout by these rules:
- `restartPointSortedBlock` (kind 'restart-point') when the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built
Use something else when:
- insert, update, or delete keys after the structure is built → knotkit/ordered-map
- turn integers, strings, or tuples into byte keys whose order matches the values → knotkit/key-encoding
- merge several sorted runs before building a block (resolve equal keys in the merged stream) → knotkit/sorted-merge
- look up keys by exact match only, with no order, seek, or range scan → Map
- a whole persistent store with writes, compaction, and crash recovery → an embedded key-value store such as SQLite, LevelDB, or RocksDB
Errors are SortedBlockInvalidInputError or SortedBlockParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/sorted-block/wire` (serializeSortedBlock, deserializeSortedBlock).
Full page: https://knotkit.jkomyno.dev/modules/sorted-block.md
Types: node_modules/knotkit/sorted-block/ and https://knotkit.jkomyno.dev/reference/knotkit/sorted-block/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/sorted-block/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/sorted-block/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/sorted-block/knotkit.capability.json)suggest a change to the source record
# knotkit/sorted-merge
> Lazily merges sorted iterables in comparator order, preserving duplicates and source order on ties.
`mergeSorted` turns any number of independently sorted iterables into one ordered stream, one item at a time. It reads one head per source to start, and after that pulls only from the source it last emitted from. Nothing is buffered beyond one item per source, so a 32-item prefix of eight posting lists reads about 32 items — not the 32,768 the lists hold. `mergeSortedAsync` applies the same plan to async streams.
time O(k) to open, then O(log(k + 1)) per item · space O(k), one cursor per source · excluding comparator cost and the input's own reads
The bound is the reason the module exists. Materializing the input makes the cost of the *input*, not the cost of the *answer*.
## One call
[Section titled “One call”](#one-call)
```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'
const merged = mergeSorted(numberOrder, [
[1, 4, 4],
[2, 4, 7],
])
Array.from(merged) // [1, 2, 4, 4, 4, 7]
```
Duplicates are kept, and an item equal to another keeps its source order — the earlier source wins the tie. That is what makes the merge usable for log-structured storage: pass newer runs first and the first record for a key is the newest one.
## Read a prefix, pay for a prefix
[Section titled “Read a prefix, pay for a prefix”](#read-a-prefix-pay-for-a-prefix)
```ts
const stream = mergeSorted(numberOrder, postingLists)
const prefix: number[] = []
for (const id of stream) {
prefix.push(id)
if (prefix.length === 32) {
break // closes every unfinished source through its own return()
}
}
```
A `break` closes the opened inputs. The merge calls `return()` once on each unfinished iterator that exposes it, and if the comparator or an input throws, it still tries to close the rest — the first cleanup error surfaces only when the merge was otherwise returning normally. That contract is what makes an early exit safe rather than merely fast.
## Merge async streams
[Section titled “Merge async streams”](#merge-async-streams)
`mergeSortedAsync` is the same merge for sources that arrive over the network — SSTable blocks streamed from object storage during a compaction or a range scan. Each source can be an `AsyncIterable` or a plain `Iterable`, mixed in one call, and the result is an `AsyncGenerator` consumed with `for await`. When a source supplies a promise-valued item, the order receives the promise. The generator yields its resolved value and closes the remaining sources if the item rejects.
```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSortedAsync } from 'knotkit/sorted-merge'
async function* remoteBlock(ids: readonly number[]): AsyncGenerator {
for (const id of ids) {
await Promise.resolve() // stands in for a network read
yield id
}
}
const merged = mergeSortedAsync(numberOrder, [remoteBlock([1, 4, 4]), [2, 4, 7]])
await Array.fromAsync(merged) // [1, 2, 4, 4, 4, 7]
```
Order, tie-breaking, and duplicates match `mergeSorted` item for item, and at most one item per source is held at a time, so no run is ever buffered whole. Two things differ because the reads are awaited:
* **The first advance primes every source at once.** It opens the sources in order, then awaits all their first reads together with `Promise.allSettled`, so eight remote runs cost one round trip to start, not eight. Every later advance awaits only the source whose item was just emitted.
* **Failures wait for in-flight reads.** If a first read rejects, the merge still lets the others settle, then awaits `return()` on every opened source that has not ended and rethrows the rejection from the earliest source. A `break` awaits `return()` once per unfinished source, one source at a time, with the same cleanup-error rule as the sync merge.
## Watch the reads
[Section titled “Watch the reads”](#watch-the-reads)
Slide the prefix and the sources; both sides of the comparison are counted on the same generated data. The merge’s “items pulled” is the number of `next()` calls it actually made, so it is a count of work, not an estimate.
Sorted sources 88Items per source 409612Prefix to read 3232
* Items pulled
—
* Comparisons
—
* Baseline reads
—
* Baseline compares
—
Input is generated with `splitmix32(42)` from `knotkit/prng`, so the panel is reproducible. Both sides are counted on the same data. The published timing for this case, with its machine and workload, is in the repository at `evidence/benchmarks/results.json` under `sorted-merge`; this panel makes no timing claim of its own.
The published timing for this workload — a 32-ID prefix across eight lists holding 32,768 IDs — is **408× faster than materializing and sorting**, and it lives at [`packages/sorted-merge/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/sorted-merge/__tests__/bench) with the raw per-repeat timings in [`evidence/benchmarks/results.json`](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/results.json). It is an algorithmic-class comparison: the baseline does more work by design. The panel above makes no timing claim at all; it counts reads, which is the part that holds on any machine.
* Read the smallest record IDs across four sorted posting lists.
* The first 16 results pull 19 of 256 input IDs.
* The merge keeps one pending ID per active list and advances the list that supplied the last result.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/sorted-merge/demo.ts) against `knotkit/sorted-merge`.
## When not to reach for it
[Section titled “When not to reach for it”](#when-not-to-reach-for-it)
* **The input is not sorted.** `mergeSorted` does not order anything; it merges under an order every input already satisfies. Sorting one input is `Array.from(input).toSorted(order)`.
* **You need a keyed store.** Keeping one item per key is a `Map`; keeping keys ordered while they change is [`knotkit/ordered-map`](/modules/ordered-map/).
* **You need insert and remove of independent items.** That is a queue or heap, not a merge — [`knotkit/heap`](/modules/heap/).
The order must be a stable total order, and the values being compared must not change while the merge is active. Both requirements are inherited from the underlying heap rather than invented here; the module README states them in full.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| --------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`mergeSorted`](/reference/knotkit/sorted-merge/functions/mergesorted/) | `Generator` | Merges a finite collection of sorted iterables by pulling from the last emitted item's source. |
| [`mergeSortedAsync`](/reference/knotkit/sorted-merge/functions/mergesortedasync/) | `AsyncGenerator, void, unknown>` | Merges a finite collection of sorted async or sync iterables, priming every source concurrently and then awaiting only the last emitted item's source. |
Cost per member. Open a row for every operation.
`mergeSorted` 3 members
| Member | Cost |
| ----------------- | -------------------------------------------- |
| `first next` | O(k) time and space for k sources |
| `subsequent next` | O(log(k + 1)) time plus one iterator advance |
| `return` | O(k) plus input cleanup |
`mergeSortedAsync` 3 members
| Member | Cost |
| ----------------- | ------------------------------------------------------------------------------ |
| `first next` | O(k) time and space for k sources, with the k first reads awaited concurrently |
| `subsequent next` | O(log(k + 1)) time plus one awaited iterator advance |
| `return` | O(k) plus input cleanup, awaited one source at a time |
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/sorted-mergeCopy prompt
```
Use knotkit/sorted-merge for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sorted-merge'.
Exports:
- `mergeSorted` → `Generator`: Merges a finite collection of sorted iterables by pulling from the last emitted item's source.
- `mergeSortedAsync` → `AsyncGenerator, void, unknown>`: Merges a finite collection of sorted async or sync iterables, priming every source concurrently and then awaiting only the last emitted item's source.
Inputs and their sources:
- item order: `Order` from `knotkit/heap`
Use something else when:
- order an input whose items arrive unsorted → Array.from(input).toSorted(order)
- keep one item per key from a stream of unsorted arrivals → Map
- insert and remove independent items from an ordered queue → knotkit/heap
Full page: https://knotkit.jkomyno.dev/modules/sorted-merge.md
Types: node_modules/knotkit/sorted-merge/ and https://knotkit.jkomyno.dev/reference/knotkit/sorted-merge/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/sorted-merge/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/sorted-merge/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/apps/docs/src/content/docs/modules/sorted-merge.mdx)suggest a change to the source record
# knotkit/static-filter
> Builds immutable Binary Fuse membership filters over a known set of byte keys, with no false negatives and fewer bytes than a Bloom filter at the same false-positive rate
## Use
[Section titled “Use”](#use)
```ts
import { binaryFuse8StaticFilter } from 'knotkit/static-filter'
const encoder = new TextEncoder()
const keys = ['user:1', 'user:2', 'user:3', 'user:2'].map((key) => encoder.encode(key))
const filter = binaryFuse8StaticFilter(keys, { seed: 42n })
filter.size // 3: the repeated key counts once
filter.mightContain(encoder.encode('user:2')) // true, for every key the filter was built from
filter.mightContain(encoder.encode('user:404')) // false, except for about 1 key in 256
filter.byteLength // 12: one byte per slot
```
static-filter.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* skip a disk or network read for a key that an immutable table or file certainly does not hold
* check membership in a set of byte keys that is known in full before the first query and never changes
* keep a membership test for millions of keys in the smallest memory a Worker or browser tab can spare
* ship a compact membership summary beside an SSTable, a static index, or a release artifact and reload it later
* pick between a 0.39% and a 0.0015% false-positive rate at 9 to 10 or 18 to 20 bits per key
## Choose a layout
[Section titled “Choose a layout”](#choose-a-layout)
| Factory | Choose when | Cost |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `binaryFuse8StaticFilter`kind `binary-fuse-8` | the key set is complete before the first query, never changes, and about one false positive per 256 absent-key probes fits the read budget | 1 byte per slot, 12,800 bytes for 10,000 keys and 61,440 for 50,000 (9.8 bits per key); 0.39% false positives |
| `binaryFuse16StaticFilter`kind `binary-fuse-16` | the key set is complete before the first query, never changes, and one false positive per 256 absent-key probes exceeds the read budget, one per 65,536 fits, and memory allows two bytes per slot | 2 bytes per slot, 25,600 bytes for 10,000 keys and 122,880 for 50,000 (19.7 bits per key); 0.0015% false positives |
[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/static-filter/README.md#performance)
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| -------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`binaryFuse8StaticFilter`](/reference/knotkit/static-filter/functions/binaryfuse8staticfilter/) | `StaticFilter` | Immutable 3-wise Binary Fuse filter with 8-bit fingerprints, built once from a known set of Uint8Array keys hashed with XXH64; repeated keys count once. |
| [`binaryFuse16StaticFilter`](/reference/knotkit/static-filter/functions/binaryfuse16staticfilter/) | `StaticFilter` | The same filter with 16-bit fingerprints: twice the bytes for a false-positive rate near 2^-16. |
Cost per member. Open a row for every operation.
`binaryFuse8StaticFilter` 3 members
| Member | Cost |
| -------------- | ---------------------------------------------- |
| `build` | O(n) expected, plus O(total key bytes) hashing |
| `mightContain` | O(key length) hash plus 3 slot reads |
| `size` | O(1) |
`binaryFuse16StaticFilter` 3 members
| Member | Cost |
| -------------- | ---------------------------------------------- |
| `build` | O(n) expected, plus O(total key bytes) hashing |
| `mightContain` | O(key length) hash plus 3 slot reads |
| `size` | O(1) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------- |
| seed, defaulting to \`0n\`, that selects the XXH64 identity every key and probe is hashed under and the first construction attempt; the same keys and seed build byte-identical filters | `bigint` | [`knotkit/hash`](/modules/hash/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `StaticFilterInvalidInputError` or `StaticFilterParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `StaticFilterInvalidInputError`
`INVALID_KEYS` `INVALID_KEY` `INVALID_SEED` `CONSTRUCTION_FAILED` `MAX_CAPACITY_EXCEEDED`
* `StaticFilterParseError`
`FOREIGN_STATIC_FILTER` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `CORRUPT_FILTER_PAYLOAD` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `INVALID_CODEC_RESULT` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, `knotkit/static-filter/wire`, so code that never saves a structure never loads a parser.
* Functions
`serializeStaticFilter`, `deserializeStaticFilter`
* Formats
binary
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| ----------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| add keys one at a time after the filter is built, or merge filters from several partitions | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| an exact set, where a false positive is unacceptable | Set |
| read back, list, or count the keys that were stored | [`knotkit/sorted-block`](/modules/sorted-block/) |
| count distinct keys or estimate how often a key occurs | [`knotkit/scalar-sketch`](/modules/scalar-sketch/) |
| membership against an adversary who can choose keys to collide, or a signed proof of membership | a cryptographic accumulator or a Merkle tree |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/static-filter/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/static-filter/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/static-filterCopy prompt
```
Use knotkit/static-filter for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/static-filter'.
Exports:
- `binaryFuse8StaticFilter` → `StaticFilter`: Immutable 3-wise Binary Fuse filter with 8-bit fingerprints, built once from a known set of Uint8Array keys hashed with XXH64; repeated keys count once.
- `binaryFuse16StaticFilter` → `StaticFilter`: The same filter with 16-bit fingerprints: twice the bytes for a false-positive rate near 2^-16.
Pick the layout by these rules:
- `binaryFuse8StaticFilter` (kind 'binary-fuse-8') when the key set is complete before the first query, never changes, and about one false positive per 256 absent-key probes fits the read budget
- `binaryFuse16StaticFilter` (kind 'binary-fuse-16') when the key set is complete before the first query, never changes, and one false positive per 256 absent-key probes exceeds the read budget, one per 65,536 fits, and memory allows two bytes per slot
Inputs and their sources:
- seed, defaulting to `0n`, that selects the XXH64 identity every key and probe is hashed under and the first construction attempt; the same keys and seed build byte-identical filters: `bigint` from `knotkit/hash`
Use something else when:
- add keys one at a time after the filter is built, or merge filters from several partitions → knotkit/scalar-sketch
- an exact set, where a false positive is unacceptable → Set
- read back, list, or count the keys that were stored → knotkit/sorted-block
- count distinct keys or estimate how often a key occurs → knotkit/scalar-sketch
- membership against an adversary who can choose keys to collide, or a signed proof of membership → a cryptographic accumulator or a Merkle tree
Errors are StaticFilterInvalidInputError or StaticFilterParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/static-filter/wire` (serializeStaticFilter, deserializeStaticFilter).
Full page: https://knotkit.jkomyno.dev/modules/static-filter.md
Types: node_modules/knotkit/static-filter/ and https://knotkit.jkomyno.dev/reference/knotkit/static-filter/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/static-filter/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/static-filter/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/static-filter/knotkit.capability.json)suggest a change to the source record
# knotkit/term-index
> Indexes tokenized documents with exact term counts and ranks matching document IDs by BM25
## Use
[Section titled “Use”](#use)
```ts
import { termIndex } from 'knotkit/term-index'
const pages = [
{ title: 'Cache guide', text: 'cache cache invalidation rules' },
{ title: 'Setup', text: 'cache setup for teams' },
{ title: 'Queues', text: 'queue jobs' },
]
const tokenize = (text: string) => text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []
const index = termIndex(pages, (page) => tokenize(page.text))
const hits = index.search(tokenize('Cache'), { limit: 2 })
hits.map(({ id }) => pages[id].title) // ['Cache guide', 'Setup']
Array.from(index.postings('cache'))
// [{ id: 0, count: 2 }, { id: 1, count: 1 }]
const setupOnly = index.search(['cache'], {
limit: 1,
eligibleIds: new Set([1]),
})
setupOnly[0].id // 1
```
term-index.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* rank documents matching any of a set of exact tokens
* restrict ranked search to eligible document IDs without changing corpus statistics
* read term counts per document and document frequencies without scanning the corpus
## Worked example
[Section titled “Worked example”](#worked-example)
* Query “cache” matches 3 of 4 help articles.
* Cache guide — 2 of 4 words match. BM25 0.506.
* Setup — 1 of 4 words match. BM25 0.374.
* Operations — 1 of 8 words match. BM25 0.271.
* Cache guide wins on repeated matches. Setup beats Operations with the same match count in fewer words.
* A one-hit search returns Cache guide overall and Operations in the operations section.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/term-index/demo.ts) against `knotkit/term-index`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ----------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
| [`termIndex`](/reference/knotkit/term-index/functions/termindex/) | `TermIndex` | Build once from an iterable of documents and a token selector. Search exact terms with BM25 and return scored input positions. |
Cost per member. Open a row for every operation.
`termIndex` 5 members
| Member | Cost |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `build` | O(n + t) expected for n documents and t input tokens |
| `documentLength` | O(1) |
| `documentFrequency` | O(1) expected |
| `postings` | O(1) expected lookup and O(1) per posting |
| `search` | O(q + u log(u + 1) + p + c log(k + 1)) expected for q query tokens, u unique known terms, p visited postings, c eligible matching documents, and k retained hits |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ----------------------------------------------------------- | ---------------------------------------------- | ------------ |
| one array of tokens for each document and its zero-based ID | `(record: R, id: number) => readonly string[]` | `the caller` |
| optional document eligibility, checked before top-k | `Pick, 'has'>` | `the caller` |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `TermIndexInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `INVALID_LIMIT` `INVALID_TERMS` `MAX_CAPACITY_EXCEEDED`
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------------------------------------- | ---------------------------------------------------- |
| find records by exact tags without storing occurrence counts | [`knotkit/inverted-index`](/modules/inverted-index/) |
| add or remove postings between searches | Map\> |
| index raw text with stemming, typo tolerance, or automatic prefix expansion | zbsearch |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/term-index/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/term-index/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/term-indexCopy prompt
```
Use knotkit/term-index for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/term-index'.
Exports:
- `termIndex` → `TermIndex`: Build once from an iterable of documents and a token selector. Search exact terms with BM25 and return scored input positions.
Inputs and their sources:
- one array of tokens for each document and its zero-based ID: `(record: R, id: number) => readonly string[]` from `the caller`
- optional document eligibility, checked before top-k: `Pick, 'has'>` from `the caller`
Use something else when:
- find records by exact tags without storing occurrence counts → knotkit/inverted-index
- add or remove postings between searches → Map>
- index raw text with stemming, typo tolerance, or automatic prefix expansion → zbsearch
Errors are TermIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/term-index.md
Types: node_modules/knotkit/term-index/ and https://knotkit.jkomyno.dev/reference/knotkit/term-index/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/term-index/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/term-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/term-index/knotkit.capability.json)suggest a change to the source record
# knotkit/trie
> Resolves delimiter-separated token keys by longest prefix in a single walk
## Use
[Section titled “Use”](#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
```
trie.ts●
ResetEditRun
```
```
```ts
const regions = uncompressedSegmentedTrie([
{ 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
[Section titled “What it solves”](#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
[Section titled “Choose a layout”](#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
[Section titled “Worked example”](#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
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| [`uncompressedSegmentedTrie`](/reference/knotkit/trie/functions/uncompressedsegmentedtrie/) | `SegmentedTrie` | Segment trie with one node per segment, each node holding a \`Map\` of children in insertion order. |
| [`compressedSegmentedTrie`](/reference/knotkit/trie/functions/compressedsegmentedtrie/) | `SegmentedTrie` | 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
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------- | -------------------------------- |
| value encoding for a binary artifact, which no artifact carries back | `ElementCodec` | [`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
[Section titled “Errors”](#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
[Section titled “Save and restore”](#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
[Section titled “When not to use it”](#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
[Section titled “Performance”](#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
[Section titled “Prompt an agent”](#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`: Segment trie with one node per segment, each node holding a `Map` of children in insertion order.
- `compressedSegmentedTrie` → `SegmentedTrie`: 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` 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
[Section titled “See also”](#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
# knotkit/wire
> Encodes bounded binary envelopes and element codecs for Knotkit structures
## Use
[Section titled “Use”](#use)
```ts
import { InvalidInputError, ParseError } from 'knotkit/errors'
import { artifactFormat } from 'knotkit/wire'
class ExampleParseError extends ParseError {
readonly moduleName = 'knotkit/example'
}
class ExampleInvalidInputError extends InvalidInputError {
readonly moduleName = 'knotkit/example'
}
const FORMAT = artifactFormat({
name: 'example',
magic: Uint8Array.of(0x4b, 0x4b, 0x45, 0x58),
payloadVersion: 1,
kindTags: { dense: 1, sparse: 2 },
sectionTags: [1],
wrongFormatHint: 'use deserializeExampleJson for object projections',
parseError: (code, detail) => new ExampleParseError(code, detail),
serializationCodes: {
INVALID_ARGUMENT: 'SERIALIZATION_LIMIT_EXCEEDED',
INVALID_STRING: 'SERIALIZATION_LIMIT_EXCEEDED',
INVALID_CODEC_RESULT: 'INVALID_CODEC_RESULT',
NON_INJECTIVE_CODEC: 'NON_INJECTIVE_CODEC',
},
invalidInputError: (code, detail) => new ExampleInvalidInputError(code, detail),
})
const bytes = FORMAT.serialize(() => ({
packageHeader: Uint8Array.of(FORMAT.kindTag('dense')),
sections: [{ tag: 1, bytes: Uint8Array.of(2, 3) }],
}))
const { packageHeader, sections } = FORMAT.deserialize(bytes)
const kind = FORMAT.kindOf(packageHeader[0])
```
wire.ts●
ResetEditRun
```
```
## What it solves
[Section titled “What it solves”](#what-it-solves)
* encode a package-identified binary artifact with validated section geometry
* declare a module's binary artifact once so every decoder runs the same prelude and raises the same codes
* encode generic values with an injected byte codec
* prove an element codec injective over a run before emitting an artifact
* share bounded little-endian wire primitives across data-structure packages
* hand closure state to a package serializer without widening its public interface
## Worked example
[Section titled “Worked example”](#worked-example)
* A 16-byte payload adds 32 bytes of framing or 56 bytes with a checksum.
* Inspected version 1 and recovered 16 payload bytes.
* The optional checksum detects accidental corruption.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/wire/demo.ts) against `knotkit/wire`.
## API
[Section titled “API”](#api)
| Export | Returns | Does |
| ------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`artifactFormat`](/reference/knotkit/wire/functions/artifactformat/) | `ArtifactFormat` | Declare a module's magic, payload version, kind tags, and section tags once; frame its payloads and run its decoder prelude. |
| [`serializeEnvelope`](/reference/knotkit/wire/functions/serializeenvelope/) | `Uint8Array` | Frame package bytes into an aligned, sectioned envelope with an optional CRC-32 integrity section. |
| [`deserializeEnvelope`](/reference/knotkit/wire/functions/deserializeenvelope/) | `WireEnvelope` | Validate envelope geometry and hand the owning package its sections. |
| [`inspectEnvelope`](/reference/knotkit/wire/functions/inspectenvelope/) | `WireEnvelopeParts` | Take a valid envelope apart into owned copies of the parts serializeEnvelope takes back, whichever module wrote it. |
| [`tamperEnvelope`](/reference/knotkit/wire/functions/tamperenvelope/) | `Uint8Array` | Copy a valid artifact and damage the copy so decoding fails for exactly one named reason. |
| [`crc32`](/reference/knotkit/wire/functions/crc32/) | `number` | Checksum the bytes an integrity section covers. |
| [`chooseIntegerWidth`](/reference/knotkit/wire/functions/chooseintegerwidth/) | `IntegerWidth` | Pick the smallest declared little-endian width that holds a maximum, so an artifact spends no bytes on headroom. |
| [`integerWidthMaximum`](/reference/knotkit/wire/functions/integerwidthmaximum/) | `number` | The largest value a declared integer width can hold. |
| [`requireSection`](/reference/knotkit/wire/functions/requiresection/) | `WireSection` | Return the only section carrying a tag, or fail with the package's geometry error. |
| [`rejectSection`](/reference/knotkit/wire/functions/rejectsection/) | `void` | Fail when an artifact carries a section tag the package's layout forbids. |
| [`stateBridge`](/reference/knotkit/wire/functions/statebridge/) | `StateBridge` | Package-scoped bridge a factory attaches its closure state through, readable by the package's serializer only. |
| [`mapWireSerializationError`](/reference/knotkit/wire/functions/mapwireserializationerror/) | `T` | Translate wire caller-contract failures into a package's own closed invalid-input codes. |
Cost per member. Open a row for every operation.
`artifactFormat` 4 members
| Member | Cost |
| ------------- | -------- |
| `serialize` | O(bytes) |
| `deserialize` | O(bytes) |
| `kindTag` | O(1) |
| `kindOf` | O(1) |
`serializeEnvelope` 1 members
| Member | Cost |
| ------------------- | -------- |
| `serializeEnvelope` | O(bytes) |
`deserializeEnvelope` 1 members
| Member | Cost |
| --------------------- | -------- |
| `deserializeEnvelope` | O(bytes) |
`inspectEnvelope` 1 members
| Member | Cost |
| ----------------- | -------- |
| `inspectEnvelope` | O(bytes) |
`tamperEnvelope` 1 members
| Member | Cost |
| ---------------- | -------- |
| `tamperEnvelope` | O(bytes) |
`crc32` 1 members
| Member | Cost |
| ------- | -------- |
| `crc32` | O(bytes) |
`chooseIntegerWidth` 1 members
| Member | Cost |
| -------------------- | ---- |
| `chooseIntegerWidth` | O(1) |
`integerWidthMaximum` 1 members
| Member | Cost |
| --------------------- | ---- |
| `integerWidthMaximum` | O(1) |
`requireSection` 1 members
| Member | Cost |
| ---------------- | ----------- |
| `requireSection` | O(sections) |
`rejectSection` 1 members
| Member | Cost |
| --------------- | ----------- |
| `rejectSection` | O(sections) |
`stateBridge` 2 members
| Member | Cost |
| --------- | ---- |
| `attach` | O(1) |
| `stateOf` | O(1) |
## What you pass in
[Section titled “What you pass in”](#what-you-pass-in)
| Input | Type | Get one from |
| ---------------------------------------------------------- | -------------------------------- | -------------------------------- |
| generic value encoding | `ElementCodec` | [`knotkit/wire`](/modules/wire/) |
| the package's own error codes a wire failure translates to | `WireSerializationCodeMap` | [`knotkit/wire`](/modules/wire/) |
## Errors
[Section titled “Errors”](#errors)
Every error this module throws is `WireInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.
* `WireInvalidInputError`
`INVALID_ARGUMENT`
* `Other`
`INVALID_STRING` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC`
## Save and restore
[Section titled “Save and restore”](#save-and-restore)
Serialization lives in a separate entrypoint, , so code that never saves a structure never loads a parser.
* Functions
`serializeEnvelope`, `deserializeEnvelope`
* Formats
binary
* Compatibility
schema-versioned, envelope v1
## When not to use it
[Section titled “When not to use it”](#when-not-to-use-it)
| If you need to… | Use instead |
| --------------------------------------------- | ------------------------------------------ |
| persist a Knotkit data structure directly | the structure package's serialize function |
| produce a human-readable persistence artifact | the structure package's Json serializer |
| compress a binary artifact | CompressionStream |
## Performance
[Section titled “Performance”](#performance)
Measured by the suite in [`packages/wire/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/wire/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.
## Prompt an agent
[Section titled “Prompt an agent”](#prompt-an-agent)
Prompt · knotkit/wireCopy prompt
```
Use knotkit/wire for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/wire'.
Exports:
- `artifactFormat` → `ArtifactFormat`: Declare a module's magic, payload version, kind tags, and section tags once; frame its payloads and run its decoder prelude.
- `serializeEnvelope` → `Uint8Array`: Frame package bytes into an aligned, sectioned envelope with an optional CRC-32 integrity section.
- `deserializeEnvelope` → `WireEnvelope`: Validate envelope geometry and hand the owning package its sections.
- `inspectEnvelope` → `WireEnvelopeParts`: Take a valid envelope apart into owned copies of the parts serializeEnvelope takes back, whichever module wrote it.
- `tamperEnvelope` → `Uint8Array`: Copy a valid artifact and damage the copy so decoding fails for exactly one named reason.
- `crc32` → `number`: Checksum the bytes an integrity section covers.
- `chooseIntegerWidth` → `IntegerWidth`: Pick the smallest declared little-endian width that holds a maximum, so an artifact spends no bytes on headroom.
- `integerWidthMaximum` → `number`: The largest value a declared integer width can hold.
- `requireSection` → `WireSection`: Return the only section carrying a tag, or fail with the package's geometry error.
- `rejectSection` → `void`: Fail when an artifact carries a section tag the package's layout forbids.
- `stateBridge` → `StateBridge`: Package-scoped bridge a factory attaches its closure state through, readable by the package's serializer only.
- `mapWireSerializationError` → `T`: Translate wire caller-contract failures into a package's own closed invalid-input codes.
Inputs and their sources:
- generic value encoding: `ElementCodec` from `knotkit/wire`
- the package's own error codes a wire failure translates to: `WireSerializationCodeMap` from `knotkit/wire`
Use something else when:
- persist a Knotkit data structure directly → the structure package's serialize function
- produce a human-readable persistence artifact → the structure package's Json serializer
- compress a binary artifact → CompressionStream
Errors are WireInvalidInputError with a `code` property. Branch on `error.code`, never on the message. Save and load through `undefined` (serializeEnvelope, deserializeEnvelope).
Full page: https://knotkit.jkomyno.dev/modules/wire.md
Types: node_modules/knotkit/wire/ and https://knotkit.jkomyno.dev/reference/knotkit/wire/
```
## See also
[Section titled “See also”](#see-also)
* [API reference](/reference/knotkit/wire/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/wire/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/wire/knotkit.capability.json)suggest a change to the source record
# Examples
> See Knotkit modules work together on routing, search, streaming, and optimization problems.
Find a route across a real road network, detect near-duplicate documents, or compact sorted runs in an LSM tree. Open an example to see how the modules fit together, what the baseline does, and how to rerun the comparison.
Filter 21 examples…ModuleEvery module (all)
[](/problems/bit-width-allocation/)
### [Bit-width allocation](/problems/bit-width-allocation/)
At nine layers, dynamic programming matches exhaustive loss in 0.0714 ms against 3.6329 ms
* [prng](/modules/prng/)
* [errors](/modules/errors/)
[](/problems/budget-allocation/)
### [Budget allocation](/problems/budget-allocation/)
Lazy greedy needs 576 gain evaluations against full-scan greedy's 22,500 at budget 75 on low-overlap (0.267 ms against 4.274 ms)
* [heap](/modules/heap/)
* [prng](/modules/prng/)
* [graph](/modules/graph/)
* [sampling](/modules/sampling/)
[](/problems/context-selection/)
### [Context selection](/problems/context-selection/)
Packing three search hits into 21 words: new-query-terms-first keeps the setup rule and the version caveat in 19 words, where rank-and-truncate drops the caveat
* [deque](/modules/deque/)
* [heap](/modules/heap/)
* [sampling](/modules/sampling/)
* [prng](/modules/prng/)
[diverse-subset-selection](/problems/diverse-subset-selection/)
### [Diverse subset selection](/problems/diverse-subset-selection/)
On a 384-result pool, greedy determinant selection covers 8.00 topics at size 8, against 1.00 for top-quality selection
* [errors](/modules/errors/)
[](/problems/live-variables/)
### [Live variables](/problems/live-variables/)
A backward worklist saves 510 of 768 block evaluations on a 256-block control-flow graph
* [graph](/modules/graph/)
* [bitset](/modules/bitset/)
* [deque](/modules/deque/)
[](/problems/lsm-compaction/)
### [LSM compaction](/problems/lsm-compaction/)
On the skewed trace at fanout 4, size-tiered writes 1.81× input bytes and searches 2.70 runs per point lookup; full-level writes 2.24× and searches 1.97
* [heap](/modules/heap/)
* [interval-index](/modules/interval-index/)
* [ordered-map](/modules/ordered-map/)
* [prng](/modules/prng/)
* [scalar-sketch](/modules/scalar-sketch/)
* [sorted-block](/modules/sorted-block/)
* [sorted-merge](/modules/sorted-merge/)
* [static-filter](/modules/static-filter/)
[](/problems/metric-tsp/)
### [Metric TSP](/problems/metric-tsp/)
MST walk at n = 442: the three graph layouts land within 5% (0.697–0.723 ms); Held-Karp solves burma14 in 2.61 ms
* [graph](/modules/graph/)
* [distance](/modules/distance/)
* [prng](/modules/prng/)
[](/problems/min-cut/)
### [Minimum cut](/problems/min-cut/)
Classic contraction on a 75-vertex graph: indexed layout 0.0251 ms against 0.0393 ms for object
* [disjoint-set](/modules/disjoint-set/)
* [prng](/modules/prng/)
[](/problems/mst/)
### [Minimum spanning tree](/problems/mst/)
At 100,000 vertices, Kruskal over indexed takes 31.31 ms against 46.58 ms for object; Prim with k=4 takes 106.11 ms against 116.08 ms for binary
* [heap](/modules/heap/)
* [disjoint-set](/modules/disjoint-set/)
* [prng](/modules/prng/)
[](/problems/near-duplicate-detection/)
### [Near-duplicate detection](/problems/near-duplicate-detection/)
On a pinned 400-document corpus, 16 bands of 4 score 77 of 79,800 possible pairs and recover all 62 pairs above 0.6
* [scalar-sketch](/modules/scalar-sketch/)
* [inverted-index](/modules/inverted-index/)
* [disjoint-set](/modules/disjoint-set/)
* [distance](/modules/distance/)
[](/problems/nearest-neighbors/)
### [Nearest neighbors](/problems/nearest-neighbors/)
On SIFT10K, HNSW at width 32 reaches 99.4% held-out recall\@10 at 0.21 ms p95, against 1.5 ms for exhaustive search
* [inverted-index](/modules/inverted-index/)
* [heap](/modules/heap/)
* [bitset](/modules/bitset/)
* [cache](/modules/cache/)
* [distance](/modules/distance/)
* [prng](/modules/prng/)
* [sampling](/modules/sampling/)
[](/problems/notification-replay/)
### [Notification replay](/problems/notification-replay/)
With 100 ranges, summaries approve 16 of 32 replays and cost a mean 43,200 bytes, against 80,000 to fetch both count arrays
* [frequency-table](/modules/frequency-table/)
* [inverted-index](/modules/inverted-index/)
[per-client-rate-limit](/problems/per-client-rate-limit/)
### [Per-client rate limit](/problems/per-client-rate-limit/)
On a 7,510-arrival trace the bounded table keeps 64 clients in at most 170 KB; the hand-written Map counter keeps 4,146 in 684 KB
* [rate-limit](/modules/rate-limit/)
[](/problems/quantized-dot-product/)
### [Quantized dot product](/problems/quantized-dot-product/)
Scoring 65,539 two-bit weights took 64.7 µs directly from packed bytes and 162.6 µs with per-call expansion
* [prng](/modules/prng/)
* [errors](/modules/errors/)
[](/problems/read-clustering/)
### [Read clustering](/problems/read-clustering/)
inline-singleton clusters in 300.1 ms and retains 5,367,998 bytes per index; map-of-sets takes 322.5 ms and retains 26,328,798
* [inverted-index](/modules/inverted-index/)
* [deque](/modules/deque/)
[](/problems/road-network/)
### [Road network routing](/problems/road-network/)
On the New York network, dijkstra from one source takes 79.0 ms on compressed-sparse-row against 27.1 ms hand-written (2.7–3.3× on search rows)
* [graph](/modules/graph/)
* [heap](/modules/heap/)
[](/problems/sliding-window-median/)
### [Sliding-window median](/problems/sliding-window-median/)
Random input at width 128: sorting each window takes 147.19 ms, a sorted array 4.04 ms, an indexed skip list 9.48 ms
* [frequency-table](/modules/frequency-table/)
* [ordered-map](/modules/ordered-map/)
[](/problems/sliding-window-minimum/)
### [Sliding-window minimum](/problems/sliding-window-minimum/)
Increasing input at width 128: the array deque takes about 0.48 ms against 8.36 ms for rescanning; on random input rescanning is faster
* [deque](/modules/deque/)
[](/problems/speculative-decoding/)
### [Speculative decoding](/problems/speculative-decoding/)
39.1% paired-latency reduction on one NVIDIA A10 for a 260K-parameter toy target and a zero-cost n-gram draft; Qwen 0.5B/1.5B was 37.4% slower
* [distribution](/modules/distribution/)
* [prng](/modules/prng/)
[](/problems/tsp/)
### [Traveling salesperson](/problems/tsp/)
Bounded complete runs: sim-grid-B-010 in 2.784 ms and sim-grid-B-050 in 6.947 ms; policy rows are too noisy to rank
* [evolution](/modules/evolution/)
* [sampling](/modules/sampling/)
* [distance](/modules/distance/)
* [prng](/modules/prng/)
[](/problems/word-ladder/)
### [Word ladder](/problems/word-ladder/)
16 shortest ladders take 0.79 ms on compressed-sparse-row against 14.12 ms on the implicit graph; packed postings retain 96.8% less memory
* [graph](/modules/graph/)
* [inverted-index](/modules/inverted-index/)
No example matches. [Find a module by task](/choosing/) instead.
## Run one yourself
[Section titled “Run one yourself”](#run-one-yourself)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit
bun install
bun run demo:problem:near-duplicate-detection
```
Results come from one machine. Expect different absolute numbers on yours.
# Bit-width allocation
> Given a storage limit and predicted losses at several precisions, choose one bit width per layer. A one-bit upgrade to a large layer can consume enough storage for two smaller upgrades. Compare exhaustive search, greedy upgrades, and exact dynamic programming on the same tables.
Given a storage limit and predicted losses at several precisions, choose one bit width per layer. A one-bit upgrade to a large layer can consume enough storage for two smaller upgrades. Compare exhaustive search, greedy upgrades, and exact dynamic programming on the same tables.
## Result
[Section titled “Result”](#result)
> At nine layers, dynamic programming matches exhaustive loss in 0.0714 ms against 3.6329 ms
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
* [`knotkit/errors`](/modules/errors/): Provides the base error classes every Knotkit package throws from, discriminated by package, category, and cause
## Figures
[Section titled “Figures”](#figures)
* 48 layers, 2064 bits available. Dynamic programming finds the minimum predicted loss of 9568 using 2064 bits.
* Greedy uses 2063 bits for loss 9583. Mean solve time: 560 µs greedy, 5.56 ms exact (M1 Pro, Bun 1.4.4).
* On the three-layer example at 31 bits, greedy chooses widths \[3, 2, 2] for loss 12. The optimum is \[2, 3, 3] for loss 9.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/bit-width-allocation/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:bit-width-allocation
```
[`problems/bit-width-allocation/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/bit-width-allocation/README.md) states the fixture, the seed, and the result table.
# Budget allocation
> Spread a budget of r units across advertising channels so that the expected number of customers reached is as large as possible. Each unit on channel `s` reaches customer `t` independently with probability `p_st`. The objective `f(x) = Σ_t 1 − Π_s (1 − p_st)^\{x_s\}` is monotone and DR-submodular on the integer lattice: a channel's next unit is worth less as more units are spent, but a second unit on one channel can still be the best move. This private workload compares full-scan greedy, lazy greedy over an injected `knotkit/heap` max-heap, and stochastic greedy over injected `knotkit/prng` randomness. It checks them against the exact optimum, enumerated on small instances, and measures how far they are from optimal with an upper bound from the objective's concave relaxation and a branch-and-bound search built on it.
Spread a budget of r units across advertising channels so that the expected number of customers reached is as large as possible. Each unit on channel `s` reaches customer `t` independently with probability `p_st`. The objective `f(x) = Σ_t 1 − Π_s (1 − p_st)^\{x_s\}` is monotone and DR-submodular on the integer lattice: a channel’s next unit is worth less as more units are spent, but a second unit on one channel can still be the best move. This private workload compares full-scan greedy, lazy greedy over an injected `knotkit/heap` max-heap, and stochastic greedy over injected `knotkit/prng` randomness. It checks them against the exact optimum, enumerated on small instances, and measures how far they are from optimal with an upper bound from the objective’s concave relaxation and a branch-and-bound search built on it.
## Result
[Section titled “Result”](#result)
> Lazy greedy needs 576 gain evaluations against full-scan greedy’s 22,500 at budget 75 on low-overlap (0.267 ms against 4.274 ms)
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
* [`knotkit/graph`](/modules/graph/): Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
* [`knotkit/sampling`](/modules/sampling/): Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
## Figures
[Section titled “Figures”](#figures)
* Same best reach (59.37 expected customers), about 52,000× faster with lazy greedy.
* There are 1,384,623 ways to spend the full budget.
* Finding the best split is NP-hard. Branch and bound can take exponential time.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:budget-allocation
```
[`problems/budget-allocation/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/README.md) states the fixture, the seed, and the result table.
# Context selection
> `densityGreedyContextSelection` keeps a selection of messages or tool results within a hard token budget as candidates arrive and expire. Callers supply token counts and a monotone submodular marginal-gain oracle.
`densityGreedyContextSelection` keeps a selection of messages or tool results within a hard token budget as candidates arrive and expire. Callers supply token counts and a monotone submodular marginal-gain oracle.
## Result
[Section titled “Result”](#result)
> Packing three search hits into 21 words: new-query-terms-first keeps the setup rule and the version caveat in 19 words, where rank-and-truncate drops the caveat
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/deque`](/modules/deque/): Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/sampling`](/modules/sampling/): Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* 3 search hits, 21 words. Keep the setup rule and the version caveat.
* Rank and truncate uses 21 words and loses the version caveat.
* Gain per word uses 18 words and loses the setup rule.
* New query terms first keeps both in 19 words.
* With only the top two hits, the version caveat never arrives. At most 1 of 2 facts survive.
*
* At 0.1× input price, the cached log replaces the search result in a 600-token prompt.
* Prompt 300 → 600 tokens. Gain 9 → 4. Estimated cost 300 → 60 full-price tokens.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/context-selection/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:context-selection
```
[`problems/context-selection/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/context-selection/README.md) states the fixture, the seed, and the result table.
# Diverse subset selection
> Pick a fixed-size set of search results that balances individual quality with coverage. This private workload compares greedy determinant selection with top-quality and uniform selection, then uses small pools to measure the effect of a biased proposal on the full subset distribution.
Pick a fixed-size set of search results that balances individual quality with coverage. This private workload compares greedy determinant selection with top-quality and uniform selection, then uses small pools to measure the effect of a biased proposal on the full subset distribution.
## Result
[Section titled “Result”](#result)
> On a 384-result pool, greedy determinant selection covers 8.00 topics at size 8, against 1.00 for top-quality selection
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/errors`](/modules/errors/): Provides the base error classes every Knotkit package throws from, discriminated by package, category, and cause
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
```
This package ships no `demo.ts`; its README lists the commands that produce the result above.
[`problems/diverse-subset-selection/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/diverse-subset-selection/README.md) states the fixture, the seed, and the result table.
# Live variables
> Which values must a compiler keep at each block boundary? On a loop header that can enter its body or return a result, the header needs the guard, the value the body will read, and the result the exit will return. This workload computes those sets twice and measures how many blocks each schedule evaluates.
Which values must a compiler keep at each block boundary? On a loop header that can enter its body or return a result, the header needs the guard, the value the body will read, and the result the exit will return. This workload computes those sets twice and measures how many blocks each schedule evaluates.
## Result
[Section titled “Result”](#result)
> A backward worklist saves 510 of 768 block evaluations on a 256-block control-flow graph
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/graph`](/modules/graph/): Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
* [`knotkit/bitset`](/modules/bitset/): Provides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks
* [`knotkit/deque`](/modules/deque/): Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
## Figures
[Section titled “Figures”](#figures)
* At 256 blocks, full sweeps evaluate 768 blocks and the predecessor worklist evaluates 258, saving 510 evaluations.
* Both schedules agree on every entry and exit set. Variables 0, 1, 2 are live on entry to the loop header.
* Both start with empty live sets and visit higher block IDs first. Only the worklist limits later visits to affected predecessors.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/live-variables/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:live-variables
```
[`problems/live-variables/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/live-variables/README.md) states the fixture, the seed, and the result table.
# LSM compaction
> Replay the same key-value workload through size-tiered and full-level compaction. On the skewed update trace at fanout 4, size-tiered writes **1.81×** the input bytes and searches **2.70** runs per point lookup. Leveling writes **2.24×** and searches **1.97** runs.
Replay the same key-value workload through size-tiered and full-level compaction. On the skewed update trace at fanout 4, size-tiered writes **1.81×** the input bytes and searches **2.70** runs per point lookup. Leveling writes **2.24×** and searches **1.97** runs.
## Result
[Section titled “Result”](#result)
> On the skewed trace at fanout 4, size-tiered writes 1.81× input bytes and searches 2.70 runs per point lookup; full-level writes 2.24× and searches 1.97
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/interval-index`](/modules/interval-index/): Indexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range
* [`knotkit/ordered-map`](/modules/ordered-map/): Stores keys in comparator order with insertion, deletion, rank, selection, ceiling, floor, and range scans in either direction, as a B-tree or an indexed skip list
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
* [`knotkit/scalar-sketch`](/modules/scalar-sketch/): Provides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains
* [`knotkit/sorted-block`](/modules/sorted-block/): Packs byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans
* [`knotkit/sorted-merge`](/modules/sorted-merge/): Lazily merges sorted iterables in comparator order, preserving duplicates and source order on ties
* [`knotkit/static-filter`](/modules/static-filter/): Builds immutable Binary Fuse membership filters over a known set of byte keys, with no false negatives and fewer bytes than a Bloom filter at the same false-positive rate
## Figures
[Section titled “Figures”](#figures)
* Skewed updates and deletes, seed 0x5eed.
* 6208 updates, 1552 point lookups, 388 range scans per policy.
* Fanout 4 of the 2–8 sweep:
* Size-tiered wrote 1.81× input bytes, searched 2.70 runs per point lookup and 4.53 per scan, retained 10,393 B.
* Leveled wrote 2.24× input bytes, searched 1.97 runs per point lookup and 3.06 per scan, retained 7,876 B.
* SSTable point lookups on the skewed trace, size-tiered compaction, fanout 4.
* get(1405) misses. 2 runs span the key. Block lookups: No filter 2, Split-block Bloom 0, Binary Fuse 8 0.
* 617 hits passed 617 run range checks; 935 misses passed 3568. A deleted key counts as a miss.
* No filter: 617 block lookups for hits, 3568 for misses; 0 B of live filter state.
* Split-block Bloom: 617 block lookups for hits, 167 for misses; 2176 B of live filter state.
* Binary Fuse 8: 617 block lookups for hits, 169 for misses; 2048 B of live filter state.
* Compaction bytes when overwriting the same 4,096 keys once. Each flush holds 64 writes, fanout 4.
* Clustered batches update consecutive keys. Spread batches interleave 16 key ranges. Counts exclude initial loading and flushes.
* Full-level: 239,616 B clustered, 238,464 B spread.
* Overlap-only: 110,592 B clustered, 366,624 B spread.
* Overlap-only rewrites fewer bytes on clustered updates. Spreading each batch across the key space reverses the result.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/lsm-compaction/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:lsm-compaction
```
[`problems/lsm-compaction/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/lsm-compaction/README.md) states the fixture, the seed, and the result table.
# Metric TSP
> Metric traveling salesperson: one exact solver and three approximations over complete distance graphs built through `knotkit/graph`'s factories. Held-Karp returns the shortest tour, the MST walk returns a tour provably within twice it when the rounded distances satisfy the triangle inequality, and closest and farthest insertion return cheap tours with no bound.
Metric traveling salesperson: one exact solver and three approximations over complete distance graphs built through `knotkit/graph`’s factories. Held-Karp returns the shortest tour, the MST walk returns a tour provably within twice it when the rounded distances satisfy the triangle inequality, and closest and farthest insertion return cheap tours with no bound.
## Result
[Section titled “Result”](#result)
> MST walk at n = 442: the three graph layouts land within 5% (0.697–0.723 ms); Held-Karp solves burma14 in 2.61 ms
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/graph`](/modules/graph/): Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
* [`knotkit/distance`](/modules/distance/): Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* From seed 42, farthest insertion matches the shortest tour of 6,859 units about 5,500× faster.
* Across 200 seeds, farthest insertion finds it 45 times and is never more than 3.25% longer.
* Held–Karp takes O(n² · 2ⁿ) time. Insertion takes O(n²) and can give longer tours.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/metric-tsp/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:metric-tsp
```
[`problems/metric-tsp/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/metric-tsp/README.md) states the fixture, the seed, and the result table.
# Minimum cut
> Global minimum cut for connected, undirected, unweighted multigraphs, implemented with classic Karger and recursive Karger–Stein over injected `knotkit/disjoint-set` layouts.
Global minimum cut for connected, undirected, unweighted multigraphs, implemented with classic Karger and recursive Karger–Stein over injected `knotkit/disjoint-set` layouts.
## Result
[Section titled “Result”](#result)
> Classic contraction on a 75-vertex graph: indexed layout 0.0251 ms against 0.0393 ms for object
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/disjoint-set`](/modules/disjoint-set/): Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* The four-cycle has a cut of 2 edges (Karger–Stein with seed 42).
* At 512 vertices the documented bounds give 903642 classic trials
* and 77 Karger–Stein runs for at most 0.1% failure.
* Measured on Apple M1 Pro, one classic trial grows as n^1.2 and one recursive run as n^3.1
* over 25 to 200 vertices, so reaching 0.1% failure takes 53–123× longer with Karger–Stein.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/min-cut/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:min-cut
```
[`problems/min-cut/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/min-cut/README.md) states the fixture, the seed, and the result table.
# Minimum spanning tree
> Minimum spanning tree, solved by Prim and Kruskal over every injected knotkit layout, by Borůvka, and by the deterministic linear-comparison algorithm of Khanna, Putterman and Song (2026), over the same vendored graphs. The data structures are compared inside a real workload instead of a micro-benchmark, and the new algorithm is measured against the classics in the unit its proof counts: weight comparisons per edge.
Minimum spanning tree, solved by Prim and Kruskal over every injected knotkit layout, by Borůvka, and by the deterministic linear-comparison algorithm of Khanna, Putterman and Song (2026), over the same vendored graphs. The data structures are compared inside a real workload instead of a micro-benchmark, and the new algorithm is measured against the classics in the unit its proof counts: weight comparisons per edge.
## Result
[Section titled “Result”](#result)
> At 100,000 vertices, Kruskal over indexed takes 31.31 ms against 46.58 ms for object; Prim with k=4 takes 106.11 ms against 116.08 ms for binary
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/disjoint-set`](/modules/disjoint-set/): Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* Mean comparisons per edge over 5 seeded graphs, from 8,000 to 256,000 edges: the certificate algorithm 8.5 to 9.3 (+0.16 per doubling), Borůvka 6.8 to 10.3 (+0.70 per doubling), Kruskal's sort 11.6 to 16.6 (+1.00 per doubling).
* From 128,000 edges on, the certificate algorithm averages fewer comparisons than Borůvka.
* The two algorithms' seed ranges overlap at 3 of 6 sizes.
* On the 10-vertex fixture, Prim returns -7430 and Kruskal returns -7430.
* Kruskal examines sorted edges until it has a spanning tree.
* Each failed union leaves the component count unchanged.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/mst/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:mst
```
[`problems/mst/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/mst/README.md) states the fixture, the seed, and the result table.
# Near-duplicate detection
> Find repeated text in a retrieval corpus with MinHash banding, exact Jaccard similarity over word windows, and connected groups. On the pinned 400-document corpus, 16 bands of 4 coordinates score 77 candidates out of 79,800 possible pairs and recover all 62 pairs above the inclusive 0.6 threshold.
Find repeated text in a retrieval corpus with MinHash banding, exact Jaccard similarity over word windows, and connected groups. On the pinned 400-document corpus, 16 bands of 4 coordinates score 77 candidates out of 79,800 possible pairs and recover all 62 pairs above the inclusive 0.6 threshold.
## Result
[Section titled “Result”](#result)
> On a pinned 400-document corpus, 16 bands of 4 score 77 of 79,800 possible pairs and recover all 62 pairs above 0.6
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/scalar-sketch`](/modules/scalar-sketch/): Provides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains
* [`knotkit/inverted-index`](/modules/inverted-index/): Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
* [`knotkit/disjoint-set`](/modules/disjoint-set/): Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts
* [`knotkit/distance`](/modules/distance/): Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees
## Figures
[Section titled “Figures”](#figures)
* MinHash banding scored 77 of 79,800 pairs.
* 62/62 reference matches recovered at Jaccard >= 0.6.
* 400 simulated documents | 16 bands x 4 rows | MinHash seed 42
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/near-duplicate-detection/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:near-duplicate-detection
```
[`problems/near-duplicate-detection/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/near-duplicate-detection/README.md) states the fixture, the seed, and the result table.
# Nearest neighbors
> Find the nearest vectors by squared Euclidean distance. Two IVF-Flat layouts isolate the cost of gathering coordinates by record position versus scanning a cluster contiguously. Residual IVF-PQ searches the same clusters using compressed vector codes. Disk-backed IVF-PQ can search a supplied set of eligible IDs. HNSW searches a hierarchy of in-memory proximity graphs. DiskANN traverses a disk-backed Vamana graph, scoring its frontier with PQ. An exhaustive scan supplies the exact answer.
Find the nearest vectors by squared Euclidean distance. Two IVF-Flat layouts isolate the cost of gathering coordinates by record position versus scanning a cluster contiguously. Residual IVF-PQ searches the same clusters using compressed vector codes. Disk-backed IVF-PQ can search a supplied set of eligible IDs. HNSW searches a hierarchy of in-memory proximity graphs. DiskANN traverses a disk-backed Vamana graph, scoring its frontier with PQ. An exhaustive scan supplies the exact answer.
## Result
[Section titled “Result”](#result)
> On SIFT10K, HNSW at width 32 reaches 99.4% held-out recall\@10 at 0.21 ms p95, against 1.5 ms for exhaustive search
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/inverted-index`](/modules/inverted-index/): Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
* [`knotkit/bitset`](/modules/bitset/): Provides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks
* [`knotkit/cache`](/modules/cache/): Bounds an in-memory key-value store by entry count or total weight, with least-recently-used, SIEVE, S3-FIFO, or caller-supplied eviction and optional expiry
* [`knotkit/distance`](/modules/distance/): Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
* [`knotkit/sampling`](/modules/sampling/): Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
## Figures
[Section titled “Figures”](#figures)
* HNSW finds 99.4% of the true top 10 with 7.1× lower p95 latency.
* Measured on 50 held-out SIFT10K queries.
* On the 2,048-vector synthetic fixture, HNSW reaches 100% recall\@10 scoring 179 vectors per query; clustered IVF-Flat needs 1,065.
* In a separate tiny replay, IVF-Flat scores 2 candidates and exhaustive search scores 4.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/nearest-neighbors/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:nearest-neighbors
```
[`problems/nearest-neighbors/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/nearest-neighbors/README.md) states the fixture, the seed, and the result table.
# Notification replay
> An operator wants to resend four webhook events and has room for eight deliveries. Three events are order updates and one is a refund. Each event goes to every subscription on its topic. With three order subscriptions and one refund subscription, the replay creates **10 deliveries** (`3 × 3 + 1 × 1`). Move two subscriptions from orders to refunds and the same batch creates **6 deliveries** (`3 × 1 + 1 × 3`). This problem checks the delivery cap before creating any of those pairs.
An operator wants to resend four webhook events and has room for eight deliveries. Three events are order updates and one is a refund. Each event goes to every subscription on its topic. With three order subscriptions and one refund subscription, the replay creates **10 deliveries** (`3 × 3 + 1 × 1`). Move two subscriptions from orders to refunds and the same batch creates **6 deliveries** (`3 × 1 + 1 × 3`). This problem checks the delivery cap before creating any of those pairs.
## Result
[Section titled “Result”](#result)
> With 100 ranges, summaries approve 16 of 32 replays and cost a mean 43,200 bytes, against 80,000 to fetch both count arrays
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/frequency-table`](/modules/frequency-table/): Maintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain
* [`knotkit/inverted-index`](/modules/inverted-index/): Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
## Figures
[Section titled “Figures”](#figures)
* Four events and four subscriptions. Delivery cap is 8.
* Most subscriptions on orders gives 10 deliveries, rejected after counting.
* Most subscriptions on refunds gives 6 deliveries, approved from topic summaries.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/notification-replay/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:notification-replay
```
[`problems/notification-replay/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/notification-replay/README.md) states the fixture, the seed, and the result table.
# Per-client rate limit
> Answer "may this client spend this weight now" for every client a trace names, without remembering every client forever. This private workload replays one seeded per-client trace through all four `knotkit/rate-limit` kinds held in a bounded `keyedRateLimitTable`, and through the fixed-window counter a server writes by hand: a `Map` from client key to `\{ windowIndex, used \}`. It reports three things per preset — decisions per second, retained bytes per client, and the most weight any one client was admitted inside one trailing window — and checks that last number against the promise each kind documents.
Answer “may this client spend this weight now” for every client a trace names, without remembering every client forever. This private workload replays one seeded per-client trace through all four `knotkit/rate-limit` kinds held in a bounded `keyedRateLimitTable`, and through the fixed-window counter a server writes by hand: a `Map` from client key to `\{ windowIndex, used \}`. It reports three things per preset — decisions per second, retained bytes per client, and the most weight any one client was admitted inside one trailing window — and checks that last number against the promise each kind documents.
## Result
[Section titled “Result”](#result)
> On a 7,510-arrival trace the bounded table keeps 64 clients in at most 170 KB; the hand-written Map counter keeps 4,146 in 684 KB
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/rate-limit`](/modules/rate-limit/): Limits each client’s request weight by a fixed window, a sliding window, or a token bucket, returning the least whole millisecond a denial must wait
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
```
This package ships no `demo.ts`; its README lists the commands that produce the result above.
[`problems/per-client-rate-limit/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/per-client-rate-limit/README.md) states the fixture, the seed, and the result table.
# Quantized dot product
> How much work does it take to multiply by a row of two-bit weights? Quantize the row once, then score the same packed bytes three ways. Quantization changes the answer once. The choice of scoring loop changes the time and temporary storage.
How much work does it take to multiply by a row of two-bit weights? Quantize the row once, then score the same packed bytes three ways. Quantization changes the answer once. The choice of scoring loop changes the time and temporary storage.
## Result
[Section titled “Result”](#result)
> Scoring 65,539 two-bit weights took 64.7 µs directly from packed bytes and 162.6 µs with per-call expansion
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
* [`knotkit/errors`](/modules/errors/): Provides the base error classes every Knotkit package throws from, discriminated by package, category, and cause
## Figures
[Section titled “Figures”](#figures)
* Four Float32 weights (16 bytes) pack into 1 byte, 0xe4.
* Reconstructed weights in input order: -0.75, -0.25, 0.25, 0.75.
* With activations \[2, -1, 3, 1], the dot product changes from -0.40 to 0.25.
* Expanded, scalar and grouped scoring give 0.25, 0.25, 0.25.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/quantized-dot-product/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:quantized-dot-product
```
[`problems/quantized-dot-product/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/quantized-dot-product/README.md) states the fixture, the seed, and the result table.
# Read clustering
> Group long transcriptome reads by the gene they came from, without a reference genome. Reads are visited from most to least reliable. Each read either joins the first representative whose minimizers cover most of it, or becomes a new representative and adds its minimizers to the index. This private workload runs that greedy loop over four minimizer index layouts, one of them built from `knotkit/inverted-index`, and checks every assignment against an independent reference.
Group long transcriptome reads by the gene they came from, without a reference genome. Reads are visited from most to least reliable. Each read either joins the first representative whose minimizers cover most of it, or becomes a new representative and adds its minimizers to the index. This private workload runs that greedy loop over four minimizer index layouts, one of them built from `knotkit/inverted-index`, and checks every assignment against an independent reference.
## Result
[Section titled “Result”](#result)
> inline-singleton clusters in 300.1 ms and retains 5,367,998 bytes per index; map-of-sets takes 322.5 ms and retains 26,328,798
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/inverted-index`](/modules/inverted-index/): Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
* [`knotkit/deque`](/modules/deque/): Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
## Figures
[Section titled “Figures”](#figures)
* Pinned synthetic fixture: 4000 reads and 910 representatives.
* 73.4% of 74391 index keys hold one posting.
* The inline-singleton layout stores one representative ID directly for those keys.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/read-clustering/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:read-clustering
```
[`problems/read-clustering/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/read-clustering/README.md) states the fixture, the seed, and the result table.
# Road network routing
> Seeded shortest-path queries over two real road networks from the 9th DIMACS Implementation Challenge, answered by `knotkit/graph`'s `dijkstra` over injected storage layouts and measured against a hand-written Dijkstra that shares no algorithm code with it.
Seeded shortest-path queries over two real road networks from the 9th DIMACS Implementation Challenge, answered by `knotkit/graph`’s `dijkstra` over injected storage layouts and measured against a hand-written Dijkstra that shares no algorithm code with it.
## Result
[Section titled “Result”](#result)
> On the New York network, dijkstra from one source takes 79.0 ms on compressed-sparse-row against 27.1 ms hand-written (2.7–3.3× on search rows)
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/graph`](/modules/graph/): Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
* [`knotkit/heap`](/modules/heap/): Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators
## Figures
[Section titled “Figures”](#figures)
* Rome round trip 1425 → 1602 → 1811 → 1773 → 1674 → 1369 → 1425 covers 57 roads and 8276 m.
* All three strategies agree on every ordered leg. The multi-target search settles 2197 vertex visits, versus 5803 pairwise and 20118 full-source.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/road-network/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:road-network
```
[`problems/road-network/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/road-network/README.md) states the fixture, the seed, and the result table.
# Sliding-window median
> Find the lower median of each full window in a numeric sequence. This private workload measures the cost of sorting each window from scratch, maintaining a sorted array, and maintaining an indexed skip list as the window slides.
Find the lower median of each full window in a numeric sequence. This private workload measures the cost of sorting each window from scratch, maintaining a sorted array, and maintaining an indexed skip list as the window slides.
## Result
[Section titled “Result”](#result)
> Random input at width 128: sorting each window takes 147.19 ms, a sorted array 4.04 ms, an indexed skip list 9.48 ms
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/frequency-table`](/modules/frequency-table/): Maintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain
* [`knotkit/ordered-map`](/modules/ordered-map/): Stores keys in comparator order with insertion, deletion, rank, selection, ceiling, floor, and range scans in either direction, as a B-tree or an indexed skip list
## Figures
[Section titled “Figures”](#figures)
* Lower medians with window width 5 on a synthetic stream with one spike.
* Sort per window, sorted array and indexed skip list agree on 12/12 windows.
* The input peaks at 71 and the rolling median peaks at 21.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/sliding-window-median/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:sliding-window-median
```
[`problems/sliding-window-median/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/sliding-window-median/README.md) states the fixture, the seed, and the result table.
# Sliding-window minimum
> Find the leftmost smallest item in each full window of a sequence. Report the first minimum, then emit a new `(value, position)` pair only when its position changes. This private workload compares rescanning on expiry with a monotonic deque backed by either storage layout from `knotkit/deque`.
Find the leftmost smallest item in each full window of a sequence. Report the first minimum, then emit a new `(value, position)` pair only when its position changes. This private workload compares rescanning on expiry with a monotonic deque backed by either storage layout from `knotkit/deque`.
## Result
[Section titled “Result”](#result)
> Increasing input at width 128: the array deque takes about 0.48 ms against 8.36 ms for rescanning; on random input rescanning is faster
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/deque`](/modules/deque/): Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window
## Figures
[Section titled “Figures”](#figures)
* The minimum expires at every step on this increasing sequence.
* At width 512: 1831935 rescan comparisons and 4095 deque comparisons.
* On seeded random input at width 512: 9705 rescan comparisons and 8164 deque comparisons.
* The deque uses bounded candidate storage to avoid rescanning a whole window.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/sliding-window-minimum/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:sliding-window-minimum
```
[`problems/sliding-window-minimum/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/sliding-window-minimum/README.md) states the fixture, the seed, and the result table.
# Speculative decoding
> A draft model predicts several next tokens so a target language model can check them in one pass. When the guesses are good, the target can commit multiple tokens per pass.
A draft model predicts several next tokens so a target language model can check them in one pass. When the guesses are good, the target can commit multiple tokens per pass.
## Result
[Section titled “Result”](#result)
> 39.1% paired-latency reduction on one NVIDIA A10 for a 260K-parameter toy target and a zero-cost n-gram draft; Qwen 0.5B/1.5B was 37.4% slower
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/distribution`](/modules/distribution/): Computes probabilities, quantiles, moments, and seeded draws for named and caller-defined distributions
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* With up to 16 guesses per batch, a matching draft needs 121 rounds for 2,048 output tokens.
* A biased draft needs 533 rounds and keeps only 17.8% of its guesses.
* CPU simulation with three possible tokens and seed 1729. Each round represents one verification batch.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/speculative-decoding/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:speculative-decoding
```
[`problems/speculative-decoding/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/speculative-decoding/README.md) states the fixture, the seed, and the result table.
# Traveling salesperson
> A deterministic evolutionary solver for symmetric Euclidean traveling-salesperson instances. It combines farthest insertion with the public selection, permutation, sampling, and evolution contracts from `knotkit`.
A deterministic evolutionary solver for symmetric Euclidean traveling-salesperson instances. It combines farthest insertion with the public selection, permutation, sampling, and evolution contracts from `knotkit`.
## Result
[Section titled “Result”](#result)
> Bounded complete runs: sim-grid-B-010 in 2.784 ms and sim-grid-B-050 in 6.947 ms; policy rows are too noisy to rank
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/evolution`](/modules/evolution/): Runs deterministic population evolution with index-based parent selection and immutable permutation operators
* [`knotkit/sampling`](/modules/sampling/): Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness
* [`knotkit/distance`](/modules/distance/): Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees
* [`knotkit/prng`](/modules/prng/): Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests
## Figures
[Section titled “Figures”](#figures)
* Over 40 generations, mean tour cost fell from 32,366 to 6,563.
* The best tour fell from 6,670 to 6,563. The run uses 50 cities and seed 42.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/tsp/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:tsp
```
[`problems/tsp/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/tsp/README.md) states the fixture, the seed, and the result table.
# Word ladder
> Shortest word ladders, distance profiles, and connected components over Knuth's Stanford GraphBase five-letter words, solved over four representations of the same graph: an implicit adjacency that stores no edge, and the three stored layouts of `knotkit/graph`.
Shortest word ladders, distance profiles, and connected components over Knuth’s Stanford GraphBase five-letter words, solved over four representations of the same graph: an implicit adjacency that stores no edge, and the three stored layouts of `knotkit/graph`.
## Result
[Section titled “Result”](#result)
> 16 shortest ladders take 0.79 ms on compressed-sparse-row against 14.12 ms on the implicit graph; packed postings retain 96.8% less memory
## Modules
[Section titled “Modules”](#modules)
* [`knotkit/graph`](/modules/graph/): Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix
* [`knotkit/inverted-index`](/modules/inverted-index/): Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists
## Figures
[Section titled “Figures”](#figures)
* chaos to order: 12 single-letter changes.
* chaos -> chaps -> chops -> coops -> corps -> cores -> codes -> coder -> cider -> eider -> elder -> older -> order
* The Stanford GraphBase dictionary has 5757 words. From chaos, 1264 are unreachable.
Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/problems/word-ladder/demo.ts) at build time, from the fixtures the benchmark uses; it reproduces the README figure.
## Reproduce
[Section titled “Reproduce”](#reproduce)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit && bun install
bun run demo:problem:word-ladder
```
[`problems/word-ladder/README.md`](https://github.com/jkomyno/knotkit/blob/main/problems/word-ladder/README.md) states the fixture, the seed, and the result table.
# Algorithms
> The methods Knotkit's structures are built to serve, with their bounds, guarantees, and the measured workload behind each claim.
An algorithm page exists where a *method* — not a data structure — is the thing worth explaining, and where the choice between two correct implementations of it is a decision a caller has to make. Each page states the bound, the guarantee, the structure the method leans on, and the workload that measured it.
| Method | Guarantee | Knotkit | Measured in |
| --------------------------------------------------------------------- | ---------------------------------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| [Monotone submodular maximization](/algorithms/submodular-selection/) | `1 − 1/e` for greedy under a cardinality limit | `heap`, `prng`, `sampling` | [`problems/budget-allocation`](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/README.md) |
## Why these are not module pages
[Section titled “Why these are not module pages”](#why-these-are-not-module-pages)
A module page answers “how do I call this and what does it cost”. An algorithm page answers “which of these two correct methods should I run, and what do I give up”. Lazy greedy and full-scan greedy are the same module call in a different shape; the difference is one comparison and an enormous constant.
The mapping from method to module is the same mapping the [router](/choosing/) performs in the other direction.
# Monotone submodular maximization
> Use a heap to make greedy selections with fewer gain evaluations, then compare the results with a full scan.
Pick a fixed number of items from a large pool to maximize a set function `f`. If `f` is monotone — adding an item never hurts — and submodular — the marginal gain of an item can only shrink as the set grows — then greedy achieves at least `1 − 1/e` (about 63.2%) of the optimal value for a normalized objective (Nemhauser, Wolsey, and Fisher, 1978).
When evaluating a gain is expensive, a heap of cached upper bounds can save most of those evaluations while keeping greedy’s guarantee. On the advertising benchmark below, lazy greedy needed 576 evaluations where a full scan needed 22,500.
## The three methods
[Section titled “The three methods”](#the-three-methods)
| Method | Gain evaluations | Guarantee | Structure it needs |
| -------------------------- | ---------------------------------------------------------- | ---------------------------- | --------------------------------- |
| Full-scan greedy | up to `k · n`, scanning every remaining candidate per pick | `1 − 1/e` | none |
| Lazy greedy (Minoux, 1978) | `n +` re-evaluations of stale roots | `1 − 1/e` (unchanged) | a max-heap of cached upper bounds |
| Stochastic greedy | `(n/k) · log(1/ε)` per step | `1 − 1/e − ε` in expectation | an injected random source |
Lazy greedy works because of submodularity itself: a cached marginal gain is an **upper bound** on the true gain now, so the heap’s root is an upper bound on the best remaining choice. Re-evaluate the root. If the fresh value still beats every other cached value, it is provably the maximum, so take it. If it dropped, put it back with its smaller value and repeat. A candidate with a fresh gain below another candidate’s cached bound may be revisited before the next pick.
time O(nc + r(c + log n)), where r counts heap iterations after initialization · space O(n), one cached gain per candidate · c is the cost of one marginal-gain evaluation
When the heap pays off
Lazy greedy adds heap maintenance. It helps when bounds stay tight enough to skip many gain evaluations, especially when each evaluation is expensive.
## What it looks like in Knotkit
[Section titled “What it looks like in Knotkit”](#what-it-looks-like-in-knotkit)
Use `maxBinaryHeap` from `knotkit/heap` to keep the candidate with the highest upper bound at the root.
lazy-greedy.ts
```ts
import { mapInputOrder, maxBinaryHeap, numberOrder } from 'knotkit/heap'
// Each candidate reaches some users; pick the two that reach the most users together.
const audiences = [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const reached = new Set()
const gainOf = (index: number): number => (audiences[index] ?? []).filter((user) => !reached.has(user)).length
interface Candidate {
readonly index: number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly gain: number
}
const byGain = mapInputOrder(numberOrder, (candidate: Candidate) => candidate.gain)
const frontier = maxBinaryHeap(
byGain,
audiences.map((_, index) => ({ index, gain: gainOf(index) })),
)
const picks: number[] = []
while (picks.length < 2) {
const top = frontier.peek()
const fresh = gainOf(top.index)
if (fresh < top.gain) {
frontier.replaceRoot({ ...top, gain: fresh }) // stale bound: lower it and look again
continue
}
frontier.pop()
picks.push(top.index)
for (const user of audiences[top.index] ?? []) {
reached.add(user)
}
}
picks // [0, 2]
reached.size // 5
```
The same snippet runs, with every stated result checked, on the guide [Pick the k items that cover the most](/guides/budgeted-coverage/).
`replaceRoot` installs the updated candidate with a single sift down. `mapInputOrder` tells the heap to compare candidates by their cached gain.
Stochastic greedy instead draws a uniform sample of candidates per step, which is where `knotkit/sampling` and an injected `knotkit/prng` source enter: the sample is reproducible from the seed, so a reported result is replayable.
## The measured workload
[Section titled “The measured workload”](#the-measured-workload)
[`problems/budget-allocation`](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/README.md) measures all three against the exact optimum on a DR-submodular lattice objective — spreading `r` units of budget across advertising channels to maximize expected reach:
* At budget 75 on the `low-overlap` instance, **lazy greedy needs 576 gain evaluations against full-scan greedy’s 22,500**, and takes **0.267 ms against 4.274 ms**.
* At 16 units, lazy greedy matches the certified optimum at every budget, and takes **27.2 µs** where branch and bound takes **733 ms** to certify that optimum.
Those are the repository’s numbers for one fixture on one machine. The address is the problem README’s [Benchmarks](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/README.md#benchmarks) section; the figure is [`reach-and-time.png`](https://github.com/jkomyno/knotkit/blob/main/problems/budget-allocation/figures/reach-and-time.png).
The same workload found the limit of the structure: the heap holds one entry per channel, so **heap arity and graph layout barely matter** there. A lazy heap pays off when the pool is large — one cached bound per candidate — not when the number of candidates is small enough that a scan is free.

Quality on the left, cost on the right. Lazy greedy pays nothing for skipping evaluations; stochastic greedy trades at most 3.69% of reach for a bounded sample per step.
# Benchmark explorer
> Every recorded Knotkit comparison, selectable, with the raw per-repeat timings behind each bar.
Recorded timings for each comparison. A bar is the median of five within-run p50s, and the whisker spans the smallest to largest of those five. Rows in grey are the reference implementation the README names. Pick a comparison and a workload; the same numbers are in [`evidence/benchmarks/results.json`](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/results.json).
ComparisonWorkloadTime axislinear
The explorer needs JavaScript. The same numbers are in[results.json](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/results.json).
* Rows
—
* Fastest
—
* Baseline
—
| Row | Median | Range |
| --- | ------ | ----- |
Measured on Node.js 26.13.1, Apple M1 Pro · Darwin 23.4.0 arm64; revision `fa46d77 + local benchmark changes`. Each point is the median of 5 repeats of within-run p50s, and the whisker spans the smallest to largest of those. Rows marked baseline are the reference implementation the README names. A ratio against a baseline is only meaningful beside what that baseline does: see [reading the baselines](/benchmarks/#reading-the-baselines).
## Reading the baselines
[Section titled “Reading the baselines”](#reading-the-baselines)
A ratio against a baseline means different things depending on what the baseline does. These are algorithmic-class comparisons, where Knotkit does less work by design, not the same algorithm in faster code:
* **Indexed priority queue** — the `heap-js` adapter finds each item by value with a linear search, removes it, then pushes the replacement. Knotkit updates the key in place through its index.
* **Sorted merge** — the baseline materializes and sorts the full input before taking 32 IDs. Knotkit merges lazily and stops after the prefix.
* **Integer bitset** — ordered iteration over a `Set` includes copying and sorting. For intersection, the manual `Set` loop counts directly while `Set.intersection().size` materializes the intersection first.
* **Inverted index** — the sorted-union baseline deduplicates through a `Set` and sorts.
* **Snapshot set** — each reference snapshot copies the current `Set` into a `Map`.
* **Disjoint set** — the `Map` of `Set`s baseline moves the smaller set into the larger one on merge.
* **Heap drain** — one panel also times sorting an array up front and reading it in order.
Where the same operation and policy run on both sides — deque, heap against `heap-js`, cache against `lru-cache`, graph traversal against a typed-array loop — a gap reflects layout and call overhead. Native operations can win: the direct array reads in the ordered-map and frequency-table panels are faster than the structures, and the gallery records that.
`bun run bench:overhead` measures interface overhead: each panel times Knotkit’s public call path against a hand-written loop of the same algorithm, so the ratio is the cost of the API rather than of the algorithm. It marks every panel `yes` or `no` for “same algorithm as the baseline”, including the losses. Its capture is local, so re-run it rather than reading a committed report.
## How these are measured
[Section titled “How these are measured”](#how-these-are-measured)
Each point is the median of five within-run p50s; each whisker spans the smallest to largest. The harness warms the implementations and repeats each comparison in the same process in registration order. Times cover a whole workload invocation, including construction where the panel says build, fill, or heapify. Read-only lookups use prebuilt structures.
These are local microbenchmarks. Results depend on the runtime, the machine, and the input distribution, and the panels are historical: one machine per gallery, recorded once. For caller workloads, run the suite yourself — `bun --bun run bench` — or read the per-problem numbers, which pin a seed and a fixture.
# Measured results
> Compare recorded workloads, inspect the baselines, and reproduce the results.
The biggest gains here come from doing less work. Lazy merge reads only enough to produce a prefix. An indexed priority queue finds each entry by value after building its index. The table shows exactly what was timed or checked.
## Workloads and baselines
[Section titled “Workloads and baselines”](#workloads-and-baselines)
| Claim | Baseline | Class | Address |
| ---------------------------------------------------- | ------------------------------------------------------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Roaring bitset intersection count, 528× faster | a manual `Set` loop over two 100,000-ID ranges | algorithmic comparison | [Bitset timings](/benchmarks/#bitset) |
| First 32 sorted IDs from eight lists, 408× faster | materialize and sort all 32,768 IDs | algorithmic comparison | [Sorted-merge timings](/benchmarks/#sorted-merge) |
| Build a queue and update all 1,000 keys, 272× faster | `heap-js` linear remove plus push | algorithmic comparison | [Priority-queue timings](/benchmarks/#priority-queue) |
| Build 100,000 singleton sets, 164× faster | a `Map` of `Set`s | algorithmic comparison | [Disjoint-set timings](/benchmarks/#disjoint-set) |
| p-values agree with SciPy 1.15.3 to `1e-9` | SciPy’s published reference values, pinned as fixtures | statistical parity | [`__tests__/fixtures/PROVENANCE.md`](https://github.com/jkomyno/knotkit/blob/main/packages/hypothesis-test/__tests__/fixtures/PROVENANCE.md) |
| 25 TLA+ models replay against the implementations | each package’s own implementation | model conformance | [`verification/`](https://github.com/jkomyno/knotkit/tree/main/verification) |
| 43 subpaths smoke-tested in `Bun.WebView` | 33 modules plus 10 `/wire` entrypoints | browser compatibility | [CI workflow](https://github.com/jkomyno/knotkit/blob/main/.github/workflows/ci.yaml) |
| 39.1% lower latency, toy target, zero-cost draft | target-only decoding; Qwen 0.5B draft: 37.4% slower | research result | [`problems/speculative-decoding/docs/RESULTS.md`](https://github.com/jkomyno/knotkit/blob/main/problems/speculative-decoding/docs/RESULTS.md) |
Read each ratio in the context of its workload
These ratios capture differences in the work each implementation does. The [benchmark gallery](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/README.md#reading-the-baselines) names every baseline and includes panels where native JavaScript wins.
## What the measurements cover
[Section titled “What the measurements cover”](#what-the-measurements-cover)
* **One machine, one runtime, one fixture.** The figures are historical. Each problem README records its machine, seed, and command; re-run the benchmark on your target hardware before making a runtime decision from one.
* **Microbenchmarks measure the whole workload invocation**, including construction where the panel says build, fill, or heapify. They do not measure your call site.
* **Accuracy figures are fixture-bound.** The MinHash banding result — 77 of 79,800 pairs scored, all 62 matches above the 0.6 Jaccard threshold recovered — is one pinned 400-document corpus, not a guarantee for another corpus.
* **Model replay checks bounded correctness.** The TLA+ models and implementation traces check invariants such as order and multiplicity on the states they cover.
## The interface-overhead study
[Section titled “The interface-overhead study”](#the-interface-overhead-study)
`bun run bench:overhead` runs each caller workload twice: through Knotkit’s public API, and as a hand-written loop of the same algorithm. The ratio of the two medians is the interface overhead, the price of the abstraction rather than of the algorithm. Every panel is therefore audited `yes` or `no` for “same algorithm as the baseline”, and a `no` cell moves to a separate *Algorithm choice* section instead of being counted as overhead. The losses stay in. Its capture is local data: re-run the command to read the current numbers.
## Run the benchmarks yourself
[Section titled “Run the benchmarks yourself”](#run-the-benchmarks-yourself)
```bash
git clone https://github.com/jkomyno/knotkit.git && cd knotkit
bun install
bun --bun run bench
```
The recorded timings are in [the benchmark explorer](/benchmarks/).
## Where the numbers live
[Section titled “Where the numbers live”](#where-the-numbers-live)
| Artifact | Content |
| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| [`evidence/benchmarks/results.json`](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/results.json) | every row’s five within-run p50s, plus runtime and machine |
| [`evidence/benchmarks/README.md`](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/README.md) | one section per panel, stating its baseline |
| [`packages/*/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages) | the suites, deterministic and re-runnable |
| [`problems/*/README.md`](https://github.com/jkomyno/knotkit/tree/main/problems) | per-workload fixture, seed, command, and result |
| [`verification/models`](https://github.com/jkomyno/knotkit/tree/main/verification/models) | the TLA+ models checked against the code |
# Knotkit
> Composable data structures, seeded probability distributions, and SciPy-checked statistical tests, in zero-dependency TypeScript for browsers, Node.js, and Bun.
# A small, tested block for each job.
## What Python ships, in one TypeScript package.
Python ships `heapq`, `bisect`, and `scipy.stats` as standard tools. In TypeScript, teams hand-roll priority queues, maintain WebAssembly bridges, or sort a whole array to read 32 items.
Knotkit is one zero-dependency package: **32 modules** behind subpath imports, 16 probability distributions, and hypothesis tests whose p-values match SciPy 1.15.3 to `1e-9`. Each structure hands back a typed value you can pass to a service, a test, or a widget that draws what the algorithm does.
Seeded inputs make a run replayable, so the block behind a request can also redraw a figure in a lecture. Where a native `Set` or `Map` is the better answer, the module page says so.
[Read the docs→](/getting-started/)[Run this example→](/guides/reprioritize/)
schedule.ts
```ts
import { minPriorityQueue, numberOrder } from 'knotkit/heap'
// [priority, task]: the lowest priority runs first.
const queue = minPriorityQueue(numberOrder, [
[5, 'render'],
[1, 'parse'],
[3, 'layout'],
])
queue.updateKey(0, 'layout') // a user is now waiting on layout
queue.pop() // 'layout'
queue.pop() // 'parse'
queue.size // 1
```
## Less work shows up in the timings.
A lazy merge can stop after 32 IDs. An indexed queue can update a task in place. See what these choices saved on the recorded workloads. [Read the measurements and baselines →](/evidence/)
* [Count the overlap between two bitsets](/benchmarks/?workload=2#bitset)
* 528×
* faster than a manual Set loop
* [Read the first 32 sorted IDs](/benchmarks/?workload=0#sorted-merge)
* 408×
* faster than materializing and sorting all IDs
* [Build a queue and update all 1,000 priorities](/benchmarks/?workload=1#priority-queue)
* 272×
* faster than heap-js linear remove and push
* [Build 100,000 singleton sets](/benchmarks/?workload=0#disjoint-set)
* 164×
* faster than a Map of Sets
## 32 modules, one import rule.
Import a subpath and the bundle carries that module alone. Every structure is property-tested against a reference model, the TLA+ models replay against the implementations, and the statistical modules hold their p-values to SciPy 1.15.3 within `1e-9`.
Module pages draw their figures from that module's own `demo.ts`. Where the demo declares inputs, moving one reruns the module in a web worker.
### Collections
12
* [bitset→](/modules/bitset/ "Provides exact membership, cardinality, set algebra, and order statistics over unsigned 32-bit ids, in one flat bitmap or 65,536-id chunks")
* [cache→](/modules/cache/ "Bounds an in-memory key-value store by entry count or total weight, with least-recently-used, SIEVE, S3-FIFO, or caller-supplied eviction and optional expiry")
* [deque→](/modules/deque/ "Queues elements at both ends in O(1) amortized time, over array and Float64Array ring buffers, with an optional fixed capacity that turns the queue into a sliding window")
* [disjoint-set→](/modules/disjoint-set/ "Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts")
* [frequency-table→](/modules/frequency-table/ "Maintains exact counts, prefix sums, range sums, and rank selection over a fixed integer domain")
* [heap→](/modules/heap/ "Provides binary and k-ary min/max heaps plus indexed priority queues, ordered by caller-supplied comparators")
* [interval-index→](/modules/interval-index/ "Indexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range")
* [ordered-map→](/modules/ordered-map/ "Stores keys in comparator order with insertion, deletion, rank, selection, ceiling, floor, and range scans in either direction, as a B-tree or an indexed skip list")
* [rate-limit→](/modules/rate-limit/ "Limits each client's request weight by a fixed window, a sliding window, or a token bucket, returning the least whole millisecond a denial must wait")
* [snapshot-set→](/modules/snapshot-set/ "Keeps every snapshot readable for the lifetime of the set, at O(1) mutation and snapshot cost")
* [sorted-block→](/modules/sorted-block/ "Packs byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans")
* [sorted-merge→](/modules/sorted-merge/ "Lazily merges sorted iterables in comparator order, preserving duplicates and source order on ties")
### Search and text
4
* [inverted-index→](/modules/inverted-index/ "Indexes records by exact keys and scans sorted record IDs for one key or the union of several, using packed posting lists")
* [prefix-index→](/modules/prefix-index/ "Enumerates a bounded number of distinct strings that start with a prefix in UTF-16 order")
* [term-index→](/modules/term-index/ "Indexes tokenized documents with exact term counts and ranks matching document IDs by BM25")
* [trie→](/modules/trie/ "Resolves delimiter-separated token keys by longest prefix in a single walk")
### Graphs and optimization
4
* [combinatorics→](/modules/combinatorics/ "Counts permutations, combinations, cycles, and set partitions exactly or in log space")
* [e-graph→](/modules/e-graph/ "Propagates equalities through expressions and extracts a minimum-cost equivalent expression")
* [evolution→](/modules/evolution/ "Runs deterministic population evolution with index-based parent selection and immutable permutation operators")
* [graph→](/modules/graph/ "Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix")
### Randomness and statistics
7
* [distance→](/modules/distance/ "Compares vectors, probability distributions, and sets and exposes each rule’s mathematical guarantees")
* [distribution→](/modules/distribution/ "Computes probabilities, quantiles, moments, and seeded draws for named and caller-defined distributions")
* [hypothesis-test→](/modules/hypothesis-test/ "Computes t-test, ANOVA, rank-test, goodness-of-fit, and exact-test p-values for counts, samples, and contingency tables")
* [prng→](/modules/prng/ "Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests")
* [sampling→](/modules/sampling/ "Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness")
* [scalar-sketch→](/modules/scalar-sketch/ "Provides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains")
* [static-filter→](/modules/static-filter/ "Builds immutable Binary Fuse membership filters over a known set of byte keys, with no false negatives and fewer bytes than a Bloom filter at the same false-positive rate")
### Serialization and utilities
5
* [cas→](/modules/cas/ "Addresses wire-envelope artifacts by content hash and stores them through an injected backend")
* [errors→](/modules/errors/ "Provides the base error classes every Knotkit package throws from, discriminated by package, category, and cause")
* [hash→](/modules/hash/ "Computes deterministic non-cryptographic XXH64 hashes, identical across browsers, Node.js, and Bun")
* [key-encoding→](/modules/key-encoding/ "Encodes integers, doubles, byte strings, strings, and tuples of them as byte keys whose unsigned byte order matches the values' order")
* [wire→](/modules/wire/ "Encodes bounded binary envelopes and element codecs for Knotkit structures")
[Search modules by task →](/choosing/)
## Four rules, in every module.
Every structure comes from a factory that hands you a typed value, and these rules decide how that value behaves, in a service and in an explainer alike.
* ### Construct a value once
A value with a rule is checked where it enters, by a constructor such as `Probability.make`, and carries a branded type from there. No caller re-asserts a number.
```
const p = Probability.make(0.95)
```
* ### Pass the seed
A random source is an argument, not a global, so a probabilistic call cannot run without the one you pass. Record the seed and the draw replays in a test, a benchmark, or someone else’s browser.
```
shuffled(splitmix32(42), cards)
```
* ### Errors carry codes
Every failure is a package error carrying a `code` from an exported list, so a `switch` that misses one added in a new release fails the typecheck.
```
if (error.code === 'EMPTY') { … }
```
* ### Choose a layout by kind
The `kind` string survives serialization and two copies of the package in one bundle, while `instanceof` survives neither.
```
roaringBitset() // kind: 'roaring'
denseBitset() // kind: 'dense'
```
[Read the conventions →](/conventions/)
## Give your agent the right API on the first try.
The module-selection skill gives your agent the available imports, layout rules, and error codes for the version you installed. Give it a task and let it look up the relevant module before it writes code.
* `/llms.txt`docs in full, abridged, or by topic
* `/modules/heap.md`the heap page in Markdown
* `knotkit/capabilities.json`shipped in the package
* `knotkit-select`skill that picks the module
[Agent setup →](/agents/)
Prompt · set up KnotkitCopy prompt
```
Set up Knotkit in this project.
1. Follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source to build and install the package. Use "bundler" or "nodenext" module resolution in TypeScript.
2. Run `npx skills add jkomyno/knotkit --skill knotkit-select` to install the skill that picks a module for a task.
3. Add this to AGENTS.md (or CLAUDE.md):
Knotkit: pick a module from node_modules/knotkit/capabilities.json, then read node_modules/knotkit//README.md. Import from 'knotkit/'; there is no root import. Create structures with the exported factory functions, branch on error.code, and pass seeds and orderings explicitly.
If something is unclear, read https://knotkit.jkomyno.dev/llms.txt.
```
## Run a guide or explore a complete solution.
Enjoying Knotkit? A star on GitHub helps more people find it.
[Browse guides](/guides/)[Explore examples](/problems/)[Star on GitHub](https://github.com/jkomyno/knotkit)
# Knotkit API reference
# API reference
[Section titled “API reference”](#api-reference)
Types and signatures for every entrypoint, generated from the TypeScript sources.
Each `knotkit/` entry is one import path. The `/wire` entries hold the save and load functions for modules that support them.
To learn what a module is for and which layout to choose, start from its [module page](/modules/).
# knotkit/bitset
## Classes
[Section titled “Classes”](#classes)
* [BitsetInvalidInputError](/reference/knotkit/bitset/classes/bitsetinvalidinputerror/)
* [BitsetParseError](/reference/knotkit/bitset/classes/bitsetparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [BitsetOptions](/reference/knotkit/bitset/interfaces/bitsetoptions/)
* [Bitset](/reference/knotkit/bitset/interfaces/bitset/)
* [BitsetFactory](/reference/knotkit/bitset/interfaces/bitsetfactory/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [BitsetKind](/reference/knotkit/bitset/type-aliases/bitsetkind/)
* [BitsetInvalidInputErrorCode](/reference/knotkit/bitset/type-aliases/bitsetinvalidinputerrorcode/)
* [BitsetParseErrorCode](/reference/knotkit/bitset/type-aliases/bitsetparseerrorcode/)
* [BitsetErrorCode](/reference/knotkit/bitset/type-aliases/bitseterrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [BITSET_KINDS](/reference/knotkit/bitset/variables/bitset_kinds/)
* [BITSET_MAX_ID](/reference/knotkit/bitset/variables/bitset_max_id/)
* [BITSET_MAX_BOUND](/reference/knotkit/bitset/variables/bitset_max_bound/)
* [BITSET_INVALID_INPUT_ERROR_CODES](/reference/knotkit/bitset/variables/bitset_invalid_input_error_codes/)
* [BITSET_PARSE_ERROR_CODES](/reference/knotkit/bitset/variables/bitset_parse_error_codes/)
* [BITSET_ERROR_CODES](/reference/knotkit/bitset/variables/bitset_error_codes/)
* [\_\_BITSET_LAYOUTS](/reference/knotkit/bitset/variables/bitset_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [denseBitset](/reference/knotkit/bitset/functions/densebitset/)
* [roaringBitset](/reference/knotkit/bitset/functions/roaringbitset/)
# BitsetInvalidInputError
Defined in: [packages/bitset/src/errors.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L55)
Thrown when a caller passes a value outside the id domain to a member that validates, a range whose start is past its end, a position a bitset cannot read, an object the package did not produce where only its own bitset will do, or a comparison operand that is not a set-like.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`BitsetInvalidInputErrorCode`](/reference/knotkit/bitset/type-aliases/bitsetinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new BitsetInvalidInputError**(`code`, `message`): `BitsetInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_ID"` | `"INVALID_RANGE"` | `"INVALID_INDEX"` | `"FOREIGN_BITSET"` | `"INVALID_OPERAND"` | `"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"SERIALIZATION_LIMIT_EXCEEDED"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`BitsetInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/bitset"`
Defined in: [packages/bitset/src/errors.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L56)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_ID"` | `"INVALID_RANGE"` | `"INVALID_INDEX"` | `"FOREIGN_BITSET"` | `"INVALID_OPERAND"` | `"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"SERIALIZATION_LIMIT_EXCEEDED"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# BitsetParseError
Defined in: [packages/bitset/src/errors.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L60)
Thrown when decoding a `serializeBitset` artifact that is malformed or internally inconsistent.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`BitsetParseErrorCode`](/reference/knotkit/bitset/type-aliases/bitsetparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new BitsetParseError**(`code`, `message`): `BitsetParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_ID_SEQUENCE"` | `"CARDINALITY_MISMATCH"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`BitsetParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/bitset"`
Defined in: [packages/bitset/src/errors.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L61)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_ID_SEQUENCE"` | `"CARDINALITY_MISMATCH"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
# denseBitset
> **denseBitset**(`options?`): [`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
Defined in: [packages/bitset/src/dense-bitset.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/dense-bitset.ts#L25)
A bitset of unsigned 32-bit ids over one flat bitmap.
One bit per possible id up to the largest stored id, with no chunk directory, so it is the faster layout for a set whose ids fill a compact range — and the layout whose memory follows the span rather than the content. Choose it only when the largest id is known and per-id traffic dominates.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`BitsetOptions`](/reference/knotkit/bitset/interfaces/bitsetoptions/)
Optional `items`, added as if by `add`.
## Returns
[Section titled “Returns”](#returns)
[`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ID` when an item is not in `0 … BITSET_MAX_ID`.
## Throws
[Section titled “Throws”](#throws-1)
With code `MAX_CAPACITY_EXCEEDED` when the bitmap the items span cannot be allocated.
## Example
[Section titled “Example”](#example)
```ts
const visited = denseBitset({ items: [0, 2, 4] })
visited.size // 3
visited.rank(2) // 2
```
# roaringBitset
> **roaringBitset**(`options?`): [`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
Defined in: [packages/bitset/src/roaring-bitset.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/roaring-bitset.ts#L25)
A bitset of unsigned 32-bit ids over 65,536-id chunks, each a sorted id array or an 8 KB bitmap.
This is the recommended layout: memory follows the ids actually stored, so a caller that does not yet know how far its ids range does not pay for the span. Chunked containers also make `isDisjointFrom` and `intersectionSize` stop at the first chunk that decides them.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`BitsetOptions`](/reference/knotkit/bitset/interfaces/bitsetoptions/)
Optional `items`, added as if by `add`.
## Returns
[Section titled “Returns”](#returns)
[`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ID` when an item is not in `0 … BITSET_MAX_ID`.
## Example
[Section titled “Example”](#example)
```ts
const seen = roaringBitset({ items: [3, 65_536] })
seen.has(3) // true
seen.size // 2
```
# Bitset
Defined in: [packages/bitset/src/bitset.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L48)
A growable set of unsigned 32-bit ids, and an ES set-like: it exposes `size`, a total `has`, and `keys`, so `Set.prototype.union`, `intersection`, `isSubsetOf`, `isDisjointFrom`, and `new Set(bitset)` accept it directly.
Because the id domain is closed, the structure can answer what a hash set cannot: `rank` and `ceiling` are order statistics, `at` reads by position in ascending order, and every bulk operation works a machine word at a time.
Every member is declared in property syntax so `strictFunctionTypes` keeps parameters contravariant, as in `knotkit/deque`.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"roaring"` | `"dense"`
Defined in: [packages/bitset/src/bitset.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L50)
The container layout this bitset uses: `'roaring'` or `'dense'`.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/bitset/src/bitset.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L52)
Number of stored ids. `O(1)`. The bitset is empty when this is `0`.
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`id`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L60)
Whether `id` is stored. Total: returns `false` for any value that is not an id (`-1`, `1.5`, `NaN`, a string, `2 ** 32`), as `Set.prototype.has` does for a value it does not hold. `O(1)` for `dense`; `O(log c + log n)` for a `roaring` array container and `O(log c)` for a bitmap container, where `c` is the number of occupied chunks and `n` a container’s cardinality.
#### Parameters
[Section titled “Parameters”](#parameters)
##### id
[Section titled “id”](#id)
`number`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`id`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L69)
Add `id`. `O(1)` amortized for `dense`; `O(log c + n)` for a `roaring` array container, which shifts its tail.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### id
[Section titled “id”](#id-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
Whether the id was absent.
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_ID` when `id` is not in `0 … BITSET_MAX_ID`.
#### Throws
[Section titled “Throws”](#throws-1)
With code `MAX_CAPACITY_EXCEEDED` when a `dense` bitset cannot grow its bitmap.
***
### delete
[Section titled “delete”](#delete)
> `readonly` **delete**: (`id`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L79)
Remove `id`, as [add](/reference/knotkit/bitset/interfaces/bitset/#add) costs.
Unlike `has`, this validates: a value that cannot be an id is a caller bug here, not a question with the answer `false`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### id
[Section titled “id”](#id-2)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
Whether the id was present.
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_ID` when `id` is not in `0 … BITSET_MAX_ID`.
***
### addRange
[Section titled “addRange”](#addrange)
> `readonly` **addRange**: (`start`, `end`) => `number`
Defined in: [packages/bitset/src/bitset.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L88)
Add every id in `[start, end)`. `O((end - start) / 32)` for `dense`; `O(chunks in span)` for `roaring`.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### start
[Section titled “start”](#start)
`number`
##### end
[Section titled “end”](#end)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
The number of ids whose membership changed.
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_ID` when an argument is not in `0 … 2 ** 32`, or `INVALID_RANGE` when `start > end`.
#### Throws
[Section titled “Throws”](#throws-4)
With code `MAX_CAPACITY_EXCEEDED` when a `dense` bitset cannot grow its bitmap.
***
### deleteRange
[Section titled “deleteRange”](#deleterange)
> `readonly` **deleteRange**: (`start`, `end`) => `number`
Defined in: [packages/bitset/src/bitset.ts:96](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L96)
Remove every id in `[start, end)`, as [addRange](/reference/knotkit/bitset/interfaces/bitset/#addrange) costs.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### start
[Section titled “start”](#start-1)
`number`
##### end
[Section titled “end”](#end-1)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
The number of ids whose membership changed.
#### Throws
[Section titled “Throws”](#throws-5)
With code `INVALID_ID` when an argument is not in `0 … 2 ** 32`, or `INVALID_RANGE` when `start > end`.
***
### countRange
[Section titled “countRange”](#countrange)
> `readonly` **countRange**: (`start`, `end`) => `number`
Defined in: [packages/bitset/src/bitset.ts:105](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L105)
Count the stored ids in `[start, end)`, over the same bound domain as [addRange](/reference/knotkit/bitset/interfaces/bitset/#addrange), so `countRange(0, 2 ** 32)` is `size` and an empty range is `0`. `O((end - start) / 32)` for `dense`; `O(log c + chunks in span)` for `roaring`.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### start
[Section titled “start”](#start-2)
`number`
##### end
[Section titled “end”](#end-2)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With code `INVALID_ID` when an argument is not in `0 … 2 ** 32`, or `INVALID_RANGE` when `start > end`.
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/bitset/src/bitset.ts:111](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L111)
Remove every id and release the storage that held them. `O(1)`. A `dense` bitset otherwise keeps its high-water bitmap capacity, so a largest id that comes and goes does not reallocate.
#### Returns
[Section titled “Returns”](#returns-6)
`void`
***
### addAll
[Section titled “addAll”](#addall)
> `readonly` **addAll**: (`ids`) => `number`
Defined in: [packages/bitset/src/bitset.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L127)
Add every id of `ids`.
The operand is read completely and validated before anything is added, so the call applies completely or not at all. An operand that is this package’s own `Bitset` is copied container by container, which makes `set.addAll(set)` a no-op.
A generic operand is sorted and applied a chunk at a time, so input order does not change the cost: `O(k log k)` to stage plus one merge per touched chunk.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### ids
[Section titled “ids”](#ids)
`Iterable`<`number`>
#### Returns
[Section titled “Returns”](#returns-7)
`number`
The number of ids whose membership changed.
#### Throws
[Section titled “Throws”](#throws-7)
With code `INVALID_ID` when the operand yields a value outside `0 … BITSET_MAX_ID`.
#### Throws
[Section titled “Throws”](#throws-8)
With code `MAX_CAPACITY_EXCEEDED` when a `dense` bitset cannot grow its bitmap.
***
### deleteAll
[Section titled “deleteAll”](#deleteall)
> `readonly` **deleteAll**: (`ids`) => `number`
Defined in: [packages/bitset/src/bitset.ts:134](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L134)
Remove every id of `ids`.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### ids
[Section titled “ids”](#ids-1)
`Iterable`<`number`>
#### Returns
[Section titled “Returns”](#returns-8)
`number`
The number of ids whose membership changed.
#### Throws
[Section titled “Throws”](#throws-9)
With code `INVALID_ID` when the operand yields a value outside `0 … BITSET_MAX_ID`.
***
### retainAll
[Section titled “retainAll”](#retainall)
> `readonly` **retainAll**: (`ids`) => `number`
Defined in: [packages/bitset/src/bitset.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L142)
Keep only the ids `ids` contains. The operand is read completely first, so the call applies completely or not at all.
#### Parameters
[Section titled “Parameters”](#parameters-8)
##### ids
[Section titled “ids”](#ids-2)
`Iterable`<`number`>
#### Returns
[Section titled “Returns”](#returns-9)
`number`
The number of ids whose membership changed.
#### Throws
[Section titled “Throws”](#throws-10)
With code `INVALID_ID` when the operand yields a value outside `0 … BITSET_MAX_ID`.
***
### equals
[Section titled “equals”](#equals)
> `readonly` **equals**: (`other`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:150](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L150)
Whether `other` holds exactly the ids this bitset holds. Compares cardinality first; another `Bitset` is then compared container by container, and any other set-like through its `has`.
#### Parameters
[Section titled “Parameters”](#parameters-9)
##### other
[Section titled “other”](#other)
`BitsetOperand`
#### Returns
[Section titled “Returns”](#returns-10)
`boolean`
#### Throws
[Section titled “Throws”](#throws-11)
With code `INVALID_OPERAND` when `other` is not a set-like.
***
### isSubsetOf
[Section titled “isSubsetOf”](#issubsetof)
> `readonly` **isSubsetOf**: (`other`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:156](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L156)
Whether every id of this bitset is in `other`.
#### Parameters
[Section titled “Parameters”](#parameters-10)
##### other
[Section titled “other”](#other-1)
`BitsetOperand`
#### Returns
[Section titled “Returns”](#returns-11)
`boolean`
#### Throws
[Section titled “Throws”](#throws-12)
With code `INVALID_OPERAND` when `other` is not a set-like.
***
### isDisjointFrom
[Section titled “isDisjointFrom”](#isdisjointfrom)
> `readonly` **isDisjointFrom**: (`other`) => `boolean`
Defined in: [packages/bitset/src/bitset.ts:163](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L163)
Whether this bitset and `other` share no id. Stops at the first shared chunk, or at the first shared id for a generic set-like.
#### Parameters
[Section titled “Parameters”](#parameters-11)
##### other
[Section titled “other”](#other-2)
`BitsetOperand`
#### Returns
[Section titled “Returns”](#returns-12)
`boolean`
#### Throws
[Section titled “Throws”](#throws-13)
With code `INVALID_OPERAND` when `other` is not a set-like.
***
### intersectionSize
[Section titled “intersectionSize”](#intersectionsize)
> `readonly` **intersectionSize**: (`other`) => `number`
Defined in: [packages/bitset/src/bitset.ts:170](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L170)
The number of ids this bitset shares with `other`, without allocating a third set. A generic set-like is walked from whichever side is smaller.
#### Parameters
[Section titled “Parameters”](#parameters-12)
##### other
[Section titled “other”](#other-3)
`BitsetOperand`
#### Returns
[Section titled “Returns”](#returns-13)
`number`
#### Throws
[Section titled “Throws”](#throws-14)
With code `INVALID_OPERAND` when `other` is not a set-like.
***
### at
[Section titled “at”](#at)
> `readonly` **at**: (`position`) => `number`
Defined in: [packages/bitset/src/bitset.ts:181](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L181)
Return the id at `position`: the `position`-th smallest for `0 <= position < size`, and the `-position`-th largest for `-size <= position < 0`, so `at(0)` is the smallest id and `at(-1)` the largest. The walk starts from the nearer end, so both are cheap; the cost grows with the distance from that end.
#### Parameters
[Section titled “Parameters”](#parameters-13)
##### position
[Section titled “position”](#position)
`number`
#### Returns
[Section titled “Returns”](#returns-14)
`number`
#### Throws
[Section titled “Throws”](#throws-15)
With code `INVALID_INDEX` when `position` is not an integer or falls outside `-size … size - 1`.
***
### rank
[Section titled “rank”](#rank)
> `readonly` **rank**: (`id`) => `number`
Defined in: [packages/bitset/src/bitset.ts:189](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L189)
Return the number of stored ids at or below `id`, matching Roaring’s convention: `rank(BITSET_MAX_ID) === size`, and `at(rank(id) - 1) === id` for every stored id.
#### Parameters
[Section titled “Parameters”](#parameters-14)
##### id
[Section titled “id”](#id-3)
`number`
#### Returns
[Section titled “Returns”](#returns-15)
`number`
#### Throws
[Section titled “Throws”](#throws-16)
With code `INVALID_ID` when `id` is not in `0 … BITSET_MAX_ID`.
***
### ceiling
[Section titled “ceiling”](#ceiling)
> `readonly` **ceiling**: (`bound`) => `number` | `undefined`
Defined in: [packages/bitset/src/bitset.ts:197](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L197)
Return the smallest stored id at or above `bound`, or `undefined` when none exists. Accepts the whole bound domain, so `ceiling(2 ** 32)` is always `undefined` and the scan idiom `ceiling(id + 1)` never throws.
#### Parameters
[Section titled “Parameters”](#parameters-15)
##### bound
[Section titled “bound”](#bound)
`number`
#### Returns
[Section titled “Returns”](#returns-16)
`number` | `undefined`
#### Throws
[Section titled “Throws”](#throws-17)
With code `INVALID_ID` when `bound` is not in `0 … 2 ** 32`.
***
### floor
[Section titled “floor”](#floor)
> `readonly` **floor**: (`id`) => `number` | `undefined`
Defined in: [packages/bitset/src/bitset.ts:204](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L204)
Return the largest stored id at or below `id`, or `undefined` when none exists: the mirror of [ceiling](/reference/knotkit/bitset/interfaces/bitset/#ceiling). `floor(BITSET_MAX_ID)` is the largest id.
#### Parameters
[Section titled “Parameters”](#parameters-16)
##### id
[Section titled “id”](#id-4)
`number`
#### Returns
[Section titled “Returns”](#returns-17)
`number` | `undefined`
#### Throws
[Section titled “Throws”](#throws-18)
With code `INVALID_ID` when `id` is not in `0 … BITSET_MAX_ID`.
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`number`>
Defined in: [packages/bitset/src/bitset.ts:214](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L214)
Iterate over every stored id in ascending order, lazily, allocating only the iterator’s own result object per step.
#### Returns
[Section titled “Returns”](#returns-18)
`IterableIterator`<`number`>
#### Throws
[Section titled “Throws”](#throws-19)
With code `MODIFIED_DURING_ITERATION` from any step, including the one that would report the end, taken after the bitset changed since this call returned. An iterator that has finished stays finished.
***
### keys
[Section titled “keys”](#keys)
> `readonly` **keys**: () => `IterableIterator`<`number`>
Defined in: [packages/bitset/src/bitset.ts:216](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L216)
The same function as [values](/reference/knotkit/bitset/interfaces/bitset/#values), so a bitset satisfies the ES set-like contract.
#### Returns
[Section titled “Returns”](#returns-19)
`IterableIterator`<`number`>
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<`number`>
Defined in: [packages/bitset/src/bitset.ts:218](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L218)
The same function as [values](/reference/knotkit/bitset/interfaces/bitset/#values), so `for (const id of bitset)` works.
#### Returns
[Section titled “Returns”](#returns-20)
`IterableIterator`<`number`>
# BitsetFactory
Defined in: [packages/bitset/src/bitset.ts:235](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L235)
The signature every layout fits, so one `__BITSET_LAYOUTS` table is sweepable.
> **BitsetFactory**(`options?`): [`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
Defined in: [packages/bitset/src/bitset.ts:236](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L236)
The signature every layout fits, so one `__BITSET_LAYOUTS` table is sweepable.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`BitsetOptions`](/reference/knotkit/bitset/interfaces/bitsetoptions/)
## Returns
[Section titled “Returns”](#returns)
[`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
# BitsetOptions
Defined in: [packages/bitset/src/bitset.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L7)
The options every bitset factory accepts, whatever its container layout.
The record is the same for both layouts, so a caller can switch layout by changing the factory alone.
## Properties
[Section titled “Properties”](#properties)
### items?
[Section titled “items?”](#items)
> `readonly` `optional` **items?**: `Iterable`<`number`, `any`, `any`>
Defined in: [packages/bitset/src/bitset.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L15)
Ids to add in iteration order as the bitset is built, as if by `add`.
A `Bitset` from this package is copied container by container instead of id by id, which also makes it the way to take an untouched copy of another bitset.
# BitsetErrorCode
> **BitsetErrorCode** = [`BitsetInvalidInputErrorCode`](/reference/knotkit/bitset/type-aliases/bitsetinvalidinputerrorcode/) | [`BitsetParseErrorCode`](/reference/knotkit/bitset/type-aliases/bitsetparseerrorcode/)
Defined in: [packages/bitset/src/errors.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L42)
A machine-readable error code emitted by `knotkit/bitset`.
# BitsetInvalidInputErrorCode
> **BitsetInvalidInputErrorCode** = *typeof* [`BITSET_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/bitset/variables/bitset_invalid_input_error_codes/)\[`number`]
Defined in: [packages/bitset/src/errors.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L36)
A machine-readable invalid-input code emitted by `knotkit/bitset`.
# BitsetKind
> **BitsetKind** = *typeof* [`BITSET_KINDS`](/reference/knotkit/bitset/variables/bitset_kinds/)\[`number`]
Defined in: [packages/bitset/src/bitset.ts:232](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L232)
Container layouts of the bitset factories.
# BitsetParseErrorCode
> **BitsetParseErrorCode** = *typeof* [`BITSET_PARSE_ERROR_CODES`](/reference/knotkit/bitset/variables/bitset_parse_error_codes/)\[`number`]
Defined in: [packages/bitset/src/errors.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L39)
A machine-readable parse code emitted by `knotkit/bitset`.
# BITSET_ERROR_CODES
> `const` **BITSET_ERROR_CODES**: readonly [`BitsetErrorCode`](/reference/knotkit/bitset/type-aliases/bitseterrorcode/)\[]
Defined in: [packages/bitset/src/errors.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L45)
Every code emitted by `knotkit/bitset`, in stable category order.
# BITSET_INVALID_INPUT_ERROR_CODES
> `const` **BITSET_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_ID"`, `"INVALID_RANGE"`, `"INVALID_INDEX"`, `"FOREIGN_BITSET"`, `"INVALID_OPERAND"`, `"MAX_CAPACITY_EXCEEDED"`, `"MODIFIED_DURING_ITERATION"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/bitset/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/bitset`.
# BITSET_KINDS
> `const` **BITSET_KINDS**: readonly \[`"roaring"`, `"dense"`]
Defined in: [packages/bitset/src/bitset.ts:229](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L229)
Every container layout this package provides, as a runtime value.
`roaring` is first because it is the recommended default: an agent that has not stated its id range should land on the layout whose memory follows its content. The default is stated here and in the capability record, never as an unqualified factory alias.
# __BITSET_LAYOUTS
> `const` **\_\_BITSET_LAYOUTS**: `Readonly`<`Record`<[`BitsetKind`](/reference/knotkit/bitset/type-aliases/bitsetkind/), [`BitsetFactory`](/reference/knotkit/bitset/interfaces/bitsetfactory/)>>
Defined in: [packages/bitset/src/layouts.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/layouts.ts#L13)
Every container layout this package constructs, keyed by the `kind` it reports.
Exported so a caller, a test, or a benchmark can sweep every layout without naming one, which is how the property suites prove the two containers agree. `roaring` is first for the same reason it is first in `BITSET_KINDS`.
# BITSET_MAX_BOUND
> `const` **BITSET_MAX_BOUND**: `number` = `4_294_967_296`
Defined in: [packages/bitset/src/bitset.ts:248](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L248)
The exclusive top of the id domain: `2 ** 32`.
It is a legal *bound* and never a legal id, which is what lets a range write name the whole domain and lets `ceiling` say “past the end” without a sentinel.
# BITSET_MAX_ID
> `const` **BITSET_MAX_ID**: `number` = `4_294_967_295`
Defined in: [packages/bitset/src/bitset.ts:240](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/bitset.ts#L240)
The largest storable id: `2 ** 32 - 1`, roaring’s own domain ceiling.
# BITSET_PARSE_ERROR_CODES
> `const` **BITSET_PARSE_ERROR_CODES**: readonly \[`"INVALID_PACKAGE_HEADER"`, `"UNKNOWN_KIND"`, `"INVALID_ID_SEQUENCE"`, `"CARDINALITY_MISMATCH"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`]
Defined in: [packages/bitset/src/errors.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/errors.ts#L16)
Codes carried specifically by [BitsetParseError](/reference/knotkit/bitset/classes/bitsetparseerror/).
# knotkit/bitset/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeBitsetOptions](/reference/knotkit/bitset/wire/interfaces/serializebitsetoptions/)
## Variables
[Section titled “Variables”](#variables)
* [BITSET_MAX_DECODE_DENSE_BYTES](/reference/knotkit/bitset/wire/variables/bitset_max_decode_dense_bytes/)
## Functions
[Section titled “Functions”](#functions)
* [serializeBitset](/reference/knotkit/bitset/wire/functions/serializebitset/)
* [deserializeBitset](/reference/knotkit/bitset/wire/functions/deserializebitset/)
# deserializeBitset
> **deserializeBitset**(`bytes`): [`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
Defined in: [packages/bitset/src/serialization.ts:196](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/serialization.ts#L196)
Decode bytes written by [serializeBitset](/reference/knotkit/bitset/wire/functions/serializebitset/), restoring the layout the artifact was serialized from.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
[`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
## Throws
[Section titled “Throws”](#throws)
With a code from `BITSET_PARSE_ERROR_CODES` when the payload is malformed, truncated, unsupported, over budget, or internally inconsistent.
# serializeBitset
> **serializeBitset**(`set`, `options?`): `Uint8Array`
Defined in: [packages/bitset/src/serialization.ts:123](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/serialization.ts#L123)
Serialize a bitset into canonical binary bytes that restore the same layout.
The payload is the Roaring format’s no-run layout — sorted chunk keys, a cardinality per chunk, then each chunk as a sorted 16-bit id run or a bitmap — inside a `knotkit/wire` envelope. The bytes are Knotkit’s own framing and are not RoaringFormatSpec-compatible.
## Parameters
[Section titled “Parameters”](#parameters)
### set
[Section titled “set”](#set)
[`Bitset`](/reference/knotkit/bitset/interfaces/bitset/)
### options?
[Section titled “options?”](#options)
[`SerializeBitsetOptions`](/reference/knotkit/bitset/wire/interfaces/serializebitsetoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With code `FOREIGN_BITSET` when `set` was not produced by this package, or `SERIALIZATION_LIMIT_EXCEEDED` when a `dense` bitset’s bitmap would exceed [BITSET_MAX_DECODE_DENSE_BYTES](/reference/knotkit/bitset/wire/variables/bitset_max_decode_dense_bytes/).
# SerializeBitsetOptions
Defined in: [packages/bitset/src/serialization.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/serialization.ts#L67)
Optional behavior for binary bitset serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/bitset/src/serialization.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/serialization.ts#L69)
Include a CRC-32 integrity section for accidental corruption detection.
# BITSET_MAX_DECODE_DENSE_BYTES
> `const` **BITSET_MAX_DECODE_DENSE_BYTES**: `number`
Defined in: [packages/bitset/src/serialization.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/bitset/src/serialization.ts#L64)
The largest `dense` bitmap a decoder will build, and the largest a serializer will write.
Enforced in both directions on purpose: without it a payload of a few dozen bytes could name a far chunk and make the decoder allocate the whole id domain, and an encoder could write bytes its own decoder refuses.
# knotkit/cache
## Classes
[Section titled “Classes”](#classes)
* [CacheInvalidInputError](/reference/knotkit/cache/classes/cacheinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [CacheEntry](/reference/knotkit/cache/interfaces/cacheentry/)
* [CacheTraceEvent](/reference/knotkit/cache/interfaces/cachetraceevent/)
* [CacheOptions](/reference/knotkit/cache/interfaces/cacheoptions/)
* [Cache](/reference/knotkit/cache/interfaces/cache/)
* [CacheFactory](/reference/knotkit/cache/interfaces/cachefactory/)
* [CacheVictimContext](/reference/knotkit/cache/interfaces/cachevictimcontext/)
* [CacheEvictionPolicy](/reference/knotkit/cache/interfaces/cacheevictionpolicy/)
* [CustomCacheOptions](/reference/knotkit/cache/interfaces/customcacheoptions/)
* [CustomCacheFactory](/reference/knotkit/cache/interfaces/customcachefactory/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [Clock](/reference/knotkit/cache/type-aliases/clock/)
* [CacheKind](/reference/knotkit/cache/type-aliases/cachekind/)
* [CustomCacheKind](/reference/knotkit/cache/type-aliases/customcachekind/)
* [CacheEvictionPolicyFactory](/reference/knotkit/cache/type-aliases/cacheevictionpolicyfactory/)
* [CacheInvalidInputErrorCode](/reference/knotkit/cache/type-aliases/cacheinvalidinputerrorcode/)
* [CacheErrorCode](/reference/knotkit/cache/type-aliases/cacheerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [CACHE_KINDS](/reference/knotkit/cache/variables/cache_kinds/)
* [CUSTOM_CACHE_KINDS](/reference/knotkit/cache/variables/custom_cache_kinds/)
* [CACHE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/cache/variables/cache_invalid_input_error_codes/)
* [CACHE_ERROR_CODES](/reference/knotkit/cache/variables/cache_error_codes/)
* [\_\_CACHE_LAYOUTS](/reference/knotkit/cache/variables/cache_layouts/)
* [\_\_CUSTOM_CACHE_LAYOUTS](/reference/knotkit/cache/variables/custom_cache_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [customCache](/reference/knotkit/cache/functions/customcache/)
* [leastRecentlyUsedCache](/reference/knotkit/cache/functions/leastrecentlyusedcache/)
* [s3FifoCache](/reference/knotkit/cache/functions/s3fifocache/)
* [sieveCache](/reference/knotkit/cache/functions/sievecache/)
# CacheInvalidInputError
Defined in: [packages/cache/src/errors.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L31)
Thrown when a cache is constructed with options that cannot bound it, when a write or clock reading violates the cache’s contract, or when a custom eviction policy names a victim the cache cannot evict or calls back into its own cache.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`CacheInvalidInputErrorCode`](/reference/knotkit/cache/type-aliases/cacheinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new CacheInvalidInputError**(`code`, `message`): `CacheInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"ENTRY_TOO_HEAVY"` | `"INVALID_VALUE"` | `"INVALID_TIME_TO_LIVE"` | `"MISSING_CLOCK"` | `"INVALID_CLOCK_READING"` | `"INVALID_VICTIM"` | `"REENTRANT_POLICY"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`CacheInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/cache"`
Defined in: [packages/cache/src/errors.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L32)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"ENTRY_TOO_HEAVY"` | `"INVALID_VALUE"` | `"INVALID_TIME_TO_LIVE"` | `"MISSING_CLOCK"` | `"INVALID_CLOCK_READING"` | `"INVALID_VICTIM"` | `"REENTRANT_POLICY"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# customCache
> **customCache**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/custom-cache.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/custom-cache.ts#L92)
Create a [Cache](/reference/knotkit/cache/interfaces/cache/) that evicts in the order a caller-supplied `CacheEvictionPolicy` chooses.
Choose it when none of the built-in policies fits: a cost-aware, priority, or domain-ordered eviction. The options are those of every built-in factory plus `policy`, which is called once, after the options are validated, with the validated capacity. The cache keeps owning entries, weights, expiry, and iteration; the policy sees keys only, never the cache’s storage.
The cache calls the policy synchronously:
* `added(key)` after `set` stores a key it did not hold;
* `used(key)` after `get` finds the key, or after `set` replaces it;
* `chooseVictim(context)` each time `set` needs room, before anything is removed for that eviction, then `deleted(victim)`;
* `deleted(key)` whenever a key leaves for any reason but `clear`: `delete`, eviction, or an expired entry that a read, `set`, or `deleteExpired` drops;
* `clear()`, when present, on `clear`.
`peek` and `has` never report a use; they report `deleted` only when they drop an entry they find expired. An expired victim is dropped without being returned from `set`, as with the built-in policies. A custom cache keeps no ghosts of evicted keys.
The answer of `chooseVictim` is checked before anything is removed for it: a key the cache does not hold, or the key being set, throws `INVALID_VICTIM`. While any callback runs, a call into the same cache’s `get`, `peek`, `has`, `set`, `delete`, `deleteExpired`, `clear`, `keys`, `values`, `entries`, or a step of one of their walks throws `REENTRANT_POLICY`; a step that throws it ends that walk.
An error a callback throws propagates. What it leaves behind:
* `chooseVictim` throwing, or answering an invalid key, leaves the cache unchanged when it happens on the first eviction of a `set`. When one `set` evicts several entries for a heavy write, the evictions already made stand, and were reported to `deleted`; the new value is not stored. Either way, an expired entry of the key being set may already have been dropped, which no read could have told apart.
* `deleted` throwing leaves the key in the cache: the call that was removing it stops before it does.
* `added` and `used` run after the write or read they report, so when either throws, the value is already stored and counted.
* `clear` throwing leaves every entry in place.
In each case the policy’s own bookkeeping is whatever the throwing callback left, and the cache stays usable.
Costs are those of the policy plus a constant per operation: one wrapper call and one flag check on every member, a `try`/`finally` around every callback, and one extra key lookup per eviction to validate the victim. Expect it to run slower than the built-in policies, which keep their order in the slot store’s typed arrays rather than in caller objects.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CustomCacheOptions`](/reference/knotkit/cache/interfaces/customcacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
At construction, with `INVALID_CAPACITY`, `MISSING_CLOCK`, or `INVALID_TIME_TO_LIVE` as every factory does. From `set`, `INVALID_VICTIM` as described above, besides the codes every [Cache](/reference/knotkit/cache/interfaces/cache/) member throws; from every member but `kind`, `size`, and `totalWeight`, `REENTRANT_POLICY` when called from inside a callback.
## Example
[Section titled “Example”](#example)
```ts
// Evict the oldest key first, ignoring reads: first-in, first-out.
function firstInFirstOut(): CacheEvictionPolicy {
const order = new Set()
return {
added: (key) => void order.add(key),
used: () => {},
deleted: (key) => void order.delete(key),
chooseVictim: ({ protectedKey }) => [...order].find((key) => key !== protectedKey)!,
clear: () => order.clear(),
}
}
const cache = customCache({ capacity: 2, policy: firstInFirstOut })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'a', value: 1 }]
```
# leastRecentlyUsedCache
> **leastRecentlyUsedCache**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/least-recently-used-cache.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/least-recently-used-cache.ts#L57)
Create a [Cache](/reference/knotkit/cache/interfaces/cache/) that evicts the entry used least recently.
Choose it when a key read recently is likely to be read again soon and the traffic has no long one-pass scans: a scan of keys never read again pushes every older entry out. `get` and a `set` of a key already held count as uses; `peek` and `has` do not.
`get`, `peek`, `has`, `delete`, and `set` run in O(1) average time, plus O(1) per entry `set` evicts. Iteration is O(n) over every slot allocated since the last `clear`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_CAPACITY` when `capacity` is not a positive safe integer (or, with `weigh`, not a positive finite number), `MISSING_CLOCK` when `timeToLive` comes without `clock`, or `INVALID_TIME_TO_LIVE` when `timeToLive` is not a positive finite number.
## Example
[Section titled “Example”](#example)
```ts
const cache = leastRecentlyUsedCache({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]
```
# s3FifoCache
> **s3FifoCache**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/s3-fifo-cache.ts:226](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/s3-fifo-cache.ts#L226)
Create a [Cache](/reference/knotkit/cache/interfaces/cache/) that evicts with S3-FIFO (simple, static, scalable FIFO queues).
Choose it when the traffic mixes a reused hot set with long scans of keys read once, or with many keys never read again: a new key waits in a small probationary queue, a tenth of capacity, and only a key read twice there reaches the main queue, so a scan cannot push the hot set out. Keys evicted from the probationary queue are remembered, without their values, so one that returns soon enters the main queue directly; those keys stay reachable until forgotten, at most one per entry in the main queue.
`get` and a `set` of a key already held count as uses; `peek` and `has` do not.
`get`, `peek`, `has`, and `delete` run in O(1) average time; `set` runs in O(1) amortized time per entry it evicts, since an entry is passed over at most a bounded number of times per use. Iteration is O(n) over every slot allocated since the last `clear`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_CAPACITY` when `capacity` is not a positive safe integer (or, with `weigh`, not a positive finite number), `MISSING_CLOCK` when `timeToLive` comes without `clock`, or `INVALID_TIME_TO_LIVE` when `timeToLive` is not a positive finite number.
## Example
[Section titled “Example”](#example)
```ts
const cache = s3FifoCache({ capacity: 3 })
cache.set('a', 1)
cache.set('b', 2)
cache.set('c', 3)
cache.get('a')
cache.get('a')
cache.set('d', 4) // [{ key: 'b', value: 2 }]: 'a' moved to the main queue
```
# sieveCache
> **sieveCache**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/sieve-cache.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/sieve-cache.ts#L91)
Create a [Cache](/reference/knotkit/cache/interfaces/cache/) that evicts with SIEVE (Zhang et al., NSDI ’24).
Each entry carries a visited bit that `get` sets. A hand walks from the oldest entry toward the newest, clearing set bits, and evicts the first entry whose bit is clear; it stays where it stopped for the next eviction. An entry read since the hand last passed it therefore survives one more pass, and new entries never move older ones.
Choose it as the default for skewed traffic, where a minority of keys takes most reads. During a one-pass scan of keys never read again, the hand clears each read entry once and then chases the scanned keys toward the head, evicting them rather than the read entries behind it; but when read entries fill all but one slot, the hand walks off the head, wraps to the tail, and the scan pushes out every entry not read during it. `get` and a `set` of a key already held count as uses; `peek` and `has` do not.
`get`, `peek`, `has`, and `delete` run in O(1) average time. `set` runs in O(1) amortized time per entry it evicts: the hand clears each visited bit at most once per set. Iteration is O(n) over every slot allocated since the last `clear`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_CAPACITY` when `capacity` is not a positive safe integer (or, with `weigh`, not a positive finite number), `MISSING_CLOCK` when `timeToLive` comes without `clock`, or `INVALID_TIME_TO_LIVE` when `timeToLive` is not a positive finite number.
## Example
[Section titled “Example”](#example)
```ts
const cache = sieveCache({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]
```
# Cache
Defined in: [packages/cache/src/cache.ts:109](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L109)
A bounded in-memory key-value store that evicts entries under its policy to stay within capacity.
Keys are compared with `SameValueZero`, the same equality that `Map` uses. `undefined` is not a storable value, so `get` returning `undefined` always means the key is absent or expired.
Expiry is lazy: nothing runs on a timer. An expired entry is dropped when something touches it, when the policy needs its room, or when `deleteExpired` runs; until then it still counts toward [size](/reference/knotkit/cache/interfaces/cache/#size) and [totalWeight](/reference/knotkit/cache/interfaces/cache/#totalweight).
Both type parameters are invariant: a mutable cache both consumes and produces `K` and `V`. Every callable member is declared in property syntax so `strictFunctionTypes` keeps the parameters contravariant; method-syntax parameters would compare bivariantly and let `Cache` widen into `Cache`, defeating the invariance `in out` exists to enforce.
A cache built by `customCache` adds two rules, because its policy is caller code: every member except `kind`, `size`, and `totalWeight` throws `CacheInvalidInputError` with code `REENTRANT_POLICY` when called from inside one of that cache’s own policy callbacks, and an error a policy callback throws propagates out of the member that called it.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"least-recently-used"` | `"sieve"` | `"s3-fifo"` | `"custom"`
Defined in: [packages/cache/src/cache.ts:111](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L111)
The eviction policy this cache follows: a built-in one, or `'custom'` for a caller-supplied one.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/cache/src/cache.ts:113](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L113)
Number of entries held, including expired entries nothing has touched yet. O(1).
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/cache/src/cache.ts:120](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L120)
Summed weight of the entries held, including expired entries nothing has touched yet, rounded to the nearest representable number. Capacity is enforced against the exact sum before rounding. Equals [size](/reference/knotkit/cache/interfaces/cache/#size) when the cache was built without `weigh`. O(1).
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`key`) => `V` | `undefined`
Defined in: [packages/cache/src/cache.ts:128](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L128)
Return the value stored under the key, counting the read as a use for the eviction policy, or `undefined` when the key is absent or expired.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
#### Returns
[Section titled “Returns”](#returns)
`V` | `undefined`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: (`key`) => `V` | `undefined`
Defined in: [packages/cache/src/cache.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L136)
Return the value stored under the key without counting the read as a use, or `undefined` when the key is absent or expired.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
#### Returns
[Section titled “Returns”](#returns-1)
`V` | `undefined`
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`key`) => `boolean`
Defined in: [packages/cache/src/cache.ts:144](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L144)
Return `true` when the key holds an unexpired value. Never counts as a use.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### key
[Section titled “key”](#key-2)
`K`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### set
[Section titled “set”](#set)
> `readonly` **set**: (`key`, `value`) => readonly [`CacheEntry`](/reference/knotkit/cache/interfaces/cacheentry/)<`K`, `V`>\[]
Defined in: [packages/cache/src/cache.ts:161](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L161)
Store the value under the key, replacing any value already there, after evicting what the policy chooses until the entry fits. The key just set is never evicted by its own call.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### key
[Section titled “key”](#key-3)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns-3)
readonly [`CacheEntry`](/reference/knotkit/cache/interfaces/cacheentry/)<`K`, `V`>\[]
The entries evicted to make room, in eviction order. Expired entries removed along the way are not reported. Empty when nothing was evicted.
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_VALUE` when the value is `undefined`, `INVALID_WEIGHT` when `weigh` returns anything but a positive finite number, `ENTRY_TOO_HEAVY` when the entry alone outweighs capacity, or `INVALID_CLOCK_READING` when the injected clock returns a non-finite number. The cache is unchanged after any of these. A `customCache` also throws `INVALID_VICTIM` when its policy’s `chooseVictim` names a key the cache does not hold or the key being set.
***
### delete
[Section titled “delete”](#delete)
> `readonly` **delete**: (`key`) => `boolean`
Defined in: [packages/cache/src/cache.ts:170](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L170)
Remove the key.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### key
[Section titled “key”](#key-4)
`K`
#### Returns
[Section titled “Returns”](#returns-4)
`boolean`
`true` when an unexpired entry was removed; `false` when the key was absent or had expired.
#### Throws
[Section titled “Throws”](#throws-4)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/cache/src/cache.ts:172](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L172)
Remove every entry, including any bookkeeping the policy keeps for keys it has evicted.
#### Returns
[Section titled “Returns”](#returns-5)
`void`
***
### deleteExpired
[Section titled “deleteExpired”](#deleteexpired)
> `readonly` **deleteExpired**: () => `number`
Defined in: [packages/cache/src/cache.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L180)
Remove every expired entry now.
#### Returns
[Section titled “Returns”](#returns-6)
`number`
How many entries were removed. Always 0 without `timeToLive`.
#### Throws
[Section titled “Throws”](#throws-5)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### keys
[Section titled “keys”](#keys)
> `readonly` **keys**: () => `IterableIterator`<`K`>
Defined in: [packages/cache/src/cache.ts:190](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L190)
Iterate over the key of every unexpired entry, once each, in an order the policy defines and this contract does not promise. Keys added after this call returns are not visited, even before the first step; a key replaced during the walk yields its current value, as a `Map` iterator does.
#### Returns
[Section titled “Returns”](#returns-7)
`IterableIterator`<`K`>
#### Throws
[Section titled “Throws”](#throws-6)
With code `INVALID_CLOCK_READING` from a step of the walk when the injected clock returns a non-finite number.
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`V`>
Defined in: [packages/cache/src/cache.ts:196](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L196)
Iterate over every unexpired value, in the order [keys](/reference/knotkit/cache/interfaces/cache/#keys) uses.
#### Returns
[Section titled “Returns”](#returns-8)
`IterableIterator`<`V`>
#### Throws
[Section titled “Throws”](#throws-7)
With code `INVALID_CLOCK_READING`, as [keys](/reference/knotkit/cache/interfaces/cache/#keys) does.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`<[`CacheEntry`](/reference/knotkit/cache/interfaces/cacheentry/)<`K`, `V`>>
Defined in: [packages/cache/src/cache.ts:202](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L202)
Iterate over every unexpired entry, in the order [keys](/reference/knotkit/cache/interfaces/cache/#keys) uses.
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`<[`CacheEntry`](/reference/knotkit/cache/interfaces/cacheentry/)<`K`, `V`>>
#### Throws
[Section titled “Throws”](#throws-8)
With code `INVALID_CLOCK_READING`, as [keys](/reference/knotkit/cache/interfaces/cache/#keys) does.
# CacheEntry
Defined in: [packages/cache/src/cache.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L12)
One key and the value stored under it.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### key
[Section titled “key”](#key)
> `readonly` **key**: `K`
Defined in: [packages/cache/src/cache.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L14)
The key the value is stored under.
***
### value
[Section titled “value”](#value)
> `readonly` **value**: `V`
Defined in: [packages/cache/src/cache.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L16)
The value stored under [key](/reference/knotkit/cache/interfaces/cacheentry/#key).
# CacheEvictionPolicy
Defined in: [packages/cache/src/cache.ts:276](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L276)
A caller-supplied eviction policy: the order in which a `customCache` gives up its keys.
The cache owns every entry, weight, expiry, and validation; the policy sees keys only and owns only the order it will evict them in. The cache tells it when a key becomes resident, is used, or leaves, and asks it for a victim when a `set` needs room. `peek` and `has` never report a use; like every read, they report `deleted` when they drop an entry they find expired.
Every callback runs synchronously inside a cache member, and none may call back into that cache: such a call throws `CacheInvalidInputError` with code `REENTRANT_POLICY`. Reading `size` and `totalWeight` is allowed. An error a callback throws propagates out of the cache member that called it; `customCache` documents what each one leaves behind.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Properties
[Section titled “Properties”](#properties)
### added
[Section titled “added”](#added)
> `readonly` **added**: (`key`) => `void`
Defined in: [packages/cache/src/cache.ts:278](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L278)
A key the cache did not hold became resident, through `set`.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
#### Returns
[Section titled “Returns”](#returns)
`void`
***
### used
[Section titled “used”](#used)
> `readonly` **used**: (`key`) => `void`
Defined in: [packages/cache/src/cache.ts:280](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L280)
A resident key was read with `get`, or replaced with `set`: a replacement counts as a use.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
***
### deleted
[Section titled “deleted”](#deleted)
> `readonly` **deleted**: (`key`) => `void`
Defined in: [packages/cache/src/cache.ts:285](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L285)
A resident key left the cache: deleted, dropped after it expired, or evicted. Not called for `clear`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### key
[Section titled “key”](#key-2)
`K`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
***
### chooseVictim
[Section titled “chooseVictim”](#choosevictim)
> `readonly` **chooseVictim**: (`context`) => `K`
Defined in: [packages/cache/src/cache.ts:293](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L293)
Return the resident key to evict next. Called only while the cache holds at least one key other than [CacheVictimContext.protectedKey](/reference/knotkit/cache/interfaces/cachevictimcontext/#protectedkey), and before anything is removed for it. Returning a key the cache does not hold, or the protected key, throws `INVALID_VICTIM` from `set` and leaves that eviction undone. `deleted` follows for the returned key.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### context
[Section titled “context”](#context)
[`CacheVictimContext`](/reference/knotkit/cache/interfaces/cachevictimcontext/)<`K`>
#### Returns
[Section titled “Returns”](#returns-3)
`K`
***
### clear?
[Section titled “clear?”](#clear)
> `readonly` `optional` **clear?**: () => `void`
Defined in: [packages/cache/src/cache.ts:298](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L298)
Forget every key, because the cache was cleared. A policy that keeps any per-key state must provide it: `clear` reports no `deleted` per key.
#### Returns
[Section titled “Returns”](#returns-4)
`void`
# CacheFactory
Defined in: [packages/cache/src/cache.ts:226](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L226)
Factory signature shared by every eviction policy.
> **CacheFactory**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/cache.ts:227](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L227)
Factory signature shared by every eviction policy.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
# CacheOptions
Defined in: [packages/cache/src/cache.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L49)
The options every cache factory accepts, whatever its eviction policy.
The record is the same for every policy, so a caller can switch policy by changing the factory alone.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`CustomCacheOptions`](/reference/knotkit/cache/interfaces/customcacheoptions/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/cache/src/cache.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L56)
The bound the cache keeps itself within. Without [weigh](/reference/knotkit/cache/interfaces/cacheoptions/#weigh), it counts entries and must be a positive safe integer. With [weigh](/reference/knotkit/cache/interfaces/cacheoptions/#weigh), it bounds the exact sum of the supplied binary floating-point weights and may be any positive finite number. There is no rounding tolerance at the bound.
***
### weigh?
[Section titled “weigh?”](#weigh)
> `readonly` `optional` **weigh?**: (`key`, `value`) => `number`
Defined in: [packages/cache/src/cache.ts:62](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L62)
Give one entry’s share of [capacity](/reference/knotkit/cache/interfaces/cacheoptions/#capacity). Called once per `set`, before the cache changes. The result must be a positive finite number no larger than `capacity`. Omit it to weigh every entry as 1.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns)
`number`
***
### timeToLive?
[Section titled “timeToLive?”](#timetolive)
> `readonly` `optional` **timeToLive?**: `number`
Defined in: [packages/cache/src/cache.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L68)
How long after its `set` an entry stays readable, in the milliseconds of [clock](/reference/knotkit/cache/interfaces/cacheoptions/#clock). An entry whose age has reached `timeToLive` is never returned again. Requires `clock`.
***
### clock?
[Section titled “clock?”](#clock)
> `readonly` `optional` **clock?**: [`Clock`](/reference/knotkit/cache/type-aliases/clock/)
Defined in: [packages/cache/src/cache.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L73)
The time source that [timeToLive](/reference/knotkit/cache/interfaces/cacheoptions/#timetolive) is measured against. A clock that moves backwards only delays expiry.
***
### trace?
[Section titled “trace?”](#trace)
> `readonly` `optional` **trace?**: `object`
Defined in: [packages/cache/src/cache.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L80)
Receive a [CacheTraceEvent](/reference/knotkit/cache/interfaces/cachetraceevent/) for each hit, miss, insert, update, eviction, delete, and expiry, in order, so a caller can replay or scrub the policy’s behavior. Any array fits. Omitted, the cache allocates no event objects. Events are immutable; the sink is not read by the cache.
#### push
[Section titled “push”](#push)
> `readonly` **push**: (`event`) => `unknown`
##### Parameters
[Section titled “Parameters”](#parameters-1)
###### event
[Section titled “event”](#event)
[`CacheTraceEvent`](/reference/knotkit/cache/interfaces/cachetraceevent/)<`K`>
##### Returns
[Section titled “Returns”](#returns-1)
`unknown`
# CacheTraceEvent
Defined in: [packages/cache/src/cache.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L36)
One thing a cache did, reported to [CacheOptions.trace](/reference/knotkit/cache/interfaces/cacheoptions/#trace) in the order it happened.
* `hit` and `miss`: a `get` found the key, or did not (an expired key reports `expire` first, then `miss`). `peek` and `has` report neither.
* `insert` and `update`: a `set` stored a key the cache did not hold, or replaced one it did. It follows the `evict` and `expire` events the same `set` caused.
* `evict`: the policy chose the key to make room; it is one of the entries `set` returns.
* `delete`: `delete` removed an unexpired key.
* `expire`: an entry was dropped because it had expired, by any member that found it, including `deleteExpired` and an eviction that reached it.
`clear` reports nothing.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"delete"` | `"hit"` | `"miss"` | `"insert"` | `"update"` | `"evict"` | `"expire"`
Defined in: [packages/cache/src/cache.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L38)
What the cache did.
***
### key
[Section titled “key”](#key)
> `readonly` **key**: `K`
Defined in: [packages/cache/src/cache.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L40)
The key it did it to.
# CacheVictimContext
Defined in: [packages/cache/src/cache.ts:243](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L243)
What [CacheEvictionPolicy.chooseVictim](/reference/knotkit/cache/interfaces/cacheevictionpolicy/#choosevictim) may consult while it chooses.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Properties
[Section titled “Properties”](#properties)
### protectedKey
[Section titled “protectedKey”](#protectedkey)
> `readonly` **protectedKey**: `K` | `undefined`
Defined in: [packages/cache/src/cache.ts:250](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L250)
The key being set when the cache already holds it, which must not be chosen; `undefined` when the key being set is new. A key that is itself `undefined` is indistinguishable here, so a policy over such keys must not rely on this field to tell the two apart.
***
### isExpired
[Section titled “isExpired”](#isexpired)
> `readonly` **isExpired**: (`key`) => `boolean`
Defined in: [packages/cache/src/cache.ts:257](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L257)
Return `true` when the cache holds the key and its entry has expired by the clock reading of the `set` that asked; `false` otherwise, and always without `timeToLive`. An expired victim is dropped without being reported, so returning one first spares a live entry.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
# CustomCacheFactory
Defined in: [packages/cache/src/cache.ts:315](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L315)
Factory signature of every cache built from a caller-supplied eviction policy.
> **CustomCacheFactory**<`K`, `V`>(`options`): [`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
Defined in: [packages/cache/src/cache.ts:316](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L316)
Factory signature of every cache built from a caller-supplied eviction policy.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`CustomCacheOptions`](/reference/knotkit/cache/interfaces/customcacheoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`Cache`](/reference/knotkit/cache/interfaces/cache/)<`K`, `V`>
# CustomCacheOptions
Defined in: [packages/cache/src/cache.ts:309](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L309)
[CacheOptions](/reference/knotkit/cache/interfaces/cacheoptions/), plus the eviction policy a `customCache` follows.
## Extends
[Section titled “Extends”](#extends)
* [`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/)<`K`, `V`>
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/cache/src/cache.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L56)
The bound the cache keeps itself within. Without [weigh](/reference/knotkit/cache/interfaces/cacheoptions/#weigh), it counts entries and must be a positive safe integer. With [weigh](/reference/knotkit/cache/interfaces/cacheoptions/#weigh), it bounds the exact sum of the supplied binary floating-point weights and may be any positive finite number. There is no rounding tolerance at the bound.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/).[`capacity`](/reference/knotkit/cache/interfaces/cacheoptions/#capacity)
***
### weigh?
[Section titled “weigh?”](#weigh)
> `readonly` `optional` **weigh?**: (`key`, `value`) => `number`
Defined in: [packages/cache/src/cache.ts:62](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L62)
Give one entry’s share of [capacity](/reference/knotkit/cache/interfaces/cacheoptions/#capacity). Called once per `set`, before the cache changes. The result must be a positive finite number no larger than `capacity`. Omit it to weigh every entry as 1.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns)
`number`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/).[`weigh`](/reference/knotkit/cache/interfaces/cacheoptions/#weigh)
***
### timeToLive?
[Section titled “timeToLive?”](#timetolive)
> `readonly` `optional` **timeToLive?**: `number`
Defined in: [packages/cache/src/cache.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L68)
How long after its `set` an entry stays readable, in the milliseconds of [clock](/reference/knotkit/cache/interfaces/cacheoptions/#clock). An entry whose age has reached `timeToLive` is never returned again. Requires `clock`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/).[`timeToLive`](/reference/knotkit/cache/interfaces/cacheoptions/#timetolive)
***
### clock?
[Section titled “clock?”](#clock)
> `readonly` `optional` **clock?**: [`Clock`](/reference/knotkit/cache/type-aliases/clock/)
Defined in: [packages/cache/src/cache.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L73)
The time source that [timeToLive](/reference/knotkit/cache/interfaces/cacheoptions/#timetolive) is measured against. A clock that moves backwards only delays expiry.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/).[`clock`](/reference/knotkit/cache/interfaces/cacheoptions/#clock)
***
### trace?
[Section titled “trace?”](#trace)
> `readonly` `optional` **trace?**: `object`
Defined in: [packages/cache/src/cache.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L80)
Receive a [CacheTraceEvent](/reference/knotkit/cache/interfaces/cachetraceevent/) for each hit, miss, insert, update, eviction, delete, and expiry, in order, so a caller can replay or scrub the policy’s behavior. Any array fits. Omitted, the cache allocates no event objects. Events are immutable; the sink is not read by the cache.
#### push
[Section titled “push”](#push)
> `readonly` **push**: (`event`) => `unknown`
##### Parameters
[Section titled “Parameters”](#parameters-1)
###### event
[Section titled “event”](#event)
[`CacheTraceEvent`](/reference/knotkit/cache/interfaces/cachetraceevent/)<`K`>
##### Returns
[Section titled “Returns”](#returns-1)
`unknown`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CacheOptions`](/reference/knotkit/cache/interfaces/cacheoptions/).[`trace`](/reference/knotkit/cache/interfaces/cacheoptions/#trace)
***
### policy
[Section titled “policy”](#policy)
> `readonly` **policy**: [`CacheEvictionPolicyFactory`](/reference/knotkit/cache/type-aliases/cacheevictionpolicyfactory/)<`K`>
Defined in: [packages/cache/src/cache.ts:311](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L311)
Build the cache’s eviction policy.
# CacheErrorCode
> **CacheErrorCode** = [`CacheInvalidInputErrorCode`](/reference/knotkit/cache/type-aliases/cacheinvalidinputerrorcode/)
Defined in: [packages/cache/src/errors.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L23)
A machine-readable error code emitted by `knotkit/cache`.
# CacheEvictionPolicyFactory
> **CacheEvictionPolicyFactory**<`K`> = (`capacity`) => [`CacheEvictionPolicy`](/reference/knotkit/cache/interfaces/cacheevictionpolicy/)<`K`>
Defined in: [packages/cache/src/cache.ts:306](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L306)
Build one cache’s [CacheEvictionPolicy](/reference/knotkit/cache/interfaces/cacheevictionpolicy/). Called once per cache, at construction and after the options are validated, with the validated `capacity`: in entries without `weigh`, in weight with it.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
## Returns
[Section titled “Returns”](#returns)
[`CacheEvictionPolicy`](/reference/knotkit/cache/interfaces/cacheevictionpolicy/)<`K`>
# CacheInvalidInputErrorCode
> **CacheInvalidInputErrorCode** = *typeof* [`CACHE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/cache/variables/cache_invalid_input_error_codes/)\[`number`]
Defined in: [packages/cache/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L20)
A machine-readable invalid-input code emitted by `knotkit/cache`.
# CacheKind
> **CacheKind** = *typeof* [`CACHE_KINDS`](/reference/knotkit/cache/variables/cache_kinds/)\[`number`]
Defined in: [packages/cache/src/cache.ts:223](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L223)
Eviction policies provided by this package, the ones `__CACHE_LAYOUTS` builds. A cache built from a caller-supplied policy reports a [CustomCacheKind](/reference/knotkit/cache/type-aliases/customcachekind/) instead.
# Clock
> **Clock** = () => `number`
Defined in: [packages/cache/src/cache.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L9)
Read the current time, in milliseconds on the caller’s own scale.
Only differences between readings matter, so a monotonic clock (`performance.now`) and a wall clock (`Date.now`) both work. The cache never reads time on its own: injecting the clock keeps every expiry decision replayable in a test.
## Returns
[Section titled “Returns”](#returns)
`number`
# CustomCacheKind
> **CustomCacheKind** = *typeof* [`CUSTOM_CACHE_KINDS`](/reference/knotkit/cache/variables/custom_cache_kinds/)\[`number`]
Defined in: [packages/cache/src/cache.ts:240](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L240)
The `kind` of a cache whose eviction policy the caller supplies.
# CACHE_ERROR_CODES
> `const` **CACHE_ERROR_CODES**: *typeof* [`CACHE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/cache/variables/cache_invalid_input_error_codes/) = `CACHE_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/cache/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L17)
Every machine-readable error code emitted by `knotkit/cache`.
# CACHE_INVALID_INPUT_ERROR_CODES
> `const` **CACHE_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_CAPACITY"`, `"INVALID_WEIGHT"`, `"ENTRY_TOO_HEAVY"`, `"INVALID_VALUE"`, `"INVALID_TIME_TO_LIVE"`, `"MISSING_CLOCK"`, `"INVALID_CLOCK_READING"`, `"INVALID_VICTIM"`, `"REENTRANT_POLICY"`]
Defined in: [packages/cache/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/cache`.
# CACHE_KINDS
> `const` **CACHE_KINDS**: readonly \[`"least-recently-used"`, `"sieve"`, `"s3-fifo"`]
Defined in: [packages/cache/src/cache.ts:212](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L212)
Every eviction policy this package provides, as a runtime value.
Exported so a caller can enumerate the policies exhaustively without restating them, and so [CacheKind](/reference/knotkit/cache/type-aliases/cachekind/) is derived from the list rather than duplicating it.
# __CACHE_LAYOUTS
> `const` **\_\_CACHE_LAYOUTS**: `Readonly`<`Record`<[`CacheKind`](/reference/knotkit/cache/type-aliases/cachekind/), [`CacheFactory`](/reference/knotkit/cache/interfaces/cachefactory/)>>
Defined in: [packages/cache/src/layouts.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/layouts.ts#L16)
Every eviction policy, keyed by the `kind` a cache built from it reports.
Every factory takes the same options record, so `__CACHE_LAYOUTS[kind](options)` builds any policy. Iterate this table instead of naming factories one by one: a property sweep, a benchmark, or a caller comparing policies covers every entry, and a policy added to `CACHE_KINDS` fails to typecheck until it is enrolled here too.
# CUSTOM_CACHE_KINDS
> `const` **CUSTOM_CACHE_KINDS**: readonly \[`"custom"`]
Defined in: [packages/cache/src/cache.ts:237](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/cache.ts#L237)
Every `kind` a cache built from a caller-supplied eviction policy reports.
Kept apart from [CACHE_KINDS](/reference/knotkit/cache/variables/cache_kinds/) because its factory takes a `policy` the built-in factories do not, so a sweep over `__CACHE_LAYOUTS` can build every entry from one options record.
# __CUSTOM_CACHE_LAYOUTS
> `const` **\_\_CUSTOM_CACHE_LAYOUTS**: `Readonly`<`Record`<[`CustomCacheKind`](/reference/knotkit/cache/type-aliases/customcachekind/), [`CustomCacheFactory`](/reference/knotkit/cache/interfaces/customcachefactory/)>>
Defined in: [packages/cache/src/layouts.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cache/src/layouts.ts#L28)
Every cache built from a caller-supplied eviction policy, keyed by `kind`.
Kept apart from [\_\_CACHE_LAYOUTS](/reference/knotkit/cache/variables/cache_layouts/) because its factories also take a `policy`, so one table would need a signature that fits neither call site.
# knotkit/cas
## Classes
[Section titled “Classes”](#classes)
* [CasInvalidInputError](/reference/knotkit/cas/classes/casinvalidinputerror/)
* [CasParseError](/reference/knotkit/cas/classes/casparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [Artifact](/reference/knotkit/cas/interfaces/artifact/)
* [ArtifactBackend](/reference/knotkit/cas/interfaces/artifactbackend/)
* [ContentAddressedStore](/reference/knotkit/cas/interfaces/contentaddressedstore/)
* [ContentAddressedStoreOptions](/reference/knotkit/cas/interfaces/contentaddressedstoreoptions/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [CasInvalidInputErrorCode](/reference/knotkit/cas/type-aliases/casinvalidinputerrorcode/)
* [CasParseErrorCode](/reference/knotkit/cas/type-aliases/casparseerrorcode/)
* [CasErrorCode](/reference/knotkit/cas/type-aliases/caserrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [CAS_INVALID_INPUT_ERROR_CODES](/reference/knotkit/cas/variables/cas_invalid_input_error_codes/)
* [CAS_PARSE_ERROR_CODES](/reference/knotkit/cas/variables/cas_parse_error_codes/)
* [CAS_ERROR_CODES](/reference/knotkit/cas/variables/cas_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [contentAddressedStore](/reference/knotkit/cas/functions/contentaddressedstore/)
# CasInvalidInputError
Defined in: [packages/cas/src/errors.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L64)
Thrown when a caller passes an address, hash output, or artifact the store cannot accept.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`CasInvalidInputErrorCode`](/reference/knotkit/cas/type-aliases/casinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new CasInvalidInputError**(`code`, `message`): `CasInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_ADDRESS"` | `"INVALID_HASH"` | `"INVALID_ARTIFACT"` | `"HASH_FAILURE"` | `"BACKEND_FAILURE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`CasInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/cas"`
Defined in: [packages/cas/src/errors.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L65)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_ADDRESS"` | `"INVALID_HASH"` | `"INVALID_ARTIFACT"` | `"HASH_FAILURE"` | `"BACKEND_FAILURE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# CasParseError
Defined in: [packages/cas/src/errors.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L69)
Thrown when stored bytes are not the artifact the address names, or fail wire validation.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`CasParseErrorCode`](/reference/knotkit/cas/type-aliases/casparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new CasParseError**(`code`, `message`): `CasParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
[`CasParseErrorCode`](/reference/knotkit/cas/type-aliases/casparseerrorcode/)
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`CasParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/cas"`
Defined in: [packages/cas/src/errors.ts:70](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L70)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: [`CasParseErrorCode`](/reference/knotkit/cas/type-aliases/casparseerrorcode/)
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
# contentAddressedStore
> **contentAddressedStore**(`options`): [`ContentAddressedStore`](/reference/knotkit/cas/interfaces/contentaddressedstore/)
Defined in: [packages/cas/src/content-addressed-store.ts:115](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/content-addressed-store.ts#L115)
Create a store that names each artifact by the hash of its framed bytes.
Content addressing gives three properties a plain blob key cannot. Writing the same artifact twice stores one copy, because identical bytes produce one address. Reading an address cannot return different content later without failing, because the bytes are re-hashed before decoding. And an address is portable across processes and machines that share the hash function, which is why the hash is injected rather than chosen here.
A hash collision — two artifacts, one address — is detected rather than served: `add` compares the stored bytes with the ones it was about to write, and reports `ADDRESS_COLLISION` instead of returning an address whose content is the other artifact. That check costs one read on the duplicate path, which is the price of not depending on the hash being collision-free.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`ContentAddressedStoreOptions`](/reference/knotkit/cas/interfaces/contentaddressedstoreoptions/)
The backend, the hash, and the artifact family’s magic.
## Returns
[Section titled “Returns”](#returns)
[`ContentAddressedStore`](/reference/knotkit/cas/interfaces/contentaddressedstore/)
A store whose every failure carries a code from `CAS_ERROR_CODES`.
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARTIFACT` when `options.magic` is not four bytes, since no artifact of this family could ever be valid.
# Artifact
Defined in: [packages/cas/src/artifact.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L13)
One artifact a store can address: the inputs of a `knotkit/wire` envelope, without its magic and without its optional integrity section.
The store owns both of those. One store addresses one family, so the magic is a property of the store rather than of each artifact, and the store always writes the integrity section itself so no caller can choose a framing that would address the same content differently. An artifact is opaque beyond this: the store frames and hashes it, and never looks inside a section.
## Properties
[Section titled “Properties”](#properties)
### payloadVersion
[Section titled “payloadVersion”](#payloadversion)
> `readonly` **payloadVersion**: `number`
Defined in: [packages/cas/src/artifact.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L15)
The owning package’s payload version, inside the shared envelope version.
***
### packageHeader
[Section titled “packageHeader”](#packageheader)
> `readonly` **packageHeader**: `Uint8Array`
Defined in: [packages/cas/src/artifact.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L17)
The owning package’s opaque header, up to 65,535 bytes.
***
### sections
[Section titled “sections”](#sections)
> `readonly` **sections**: readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
Defined in: [packages/cas/src/artifact.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L19)
The owned opaque sections, at most 65,535 of them.
# ArtifactBackend
Defined in: [packages/cas/src/artifact.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L37)
The storage a [ContentAddressedStore](/reference/knotkit/cas/interfaces/contentaddressedstore/) writes through.
Injected rather than bundled, because the tree ships no runtime that reads files: an in-memory `Map`, an S3 client, a `fetch`-backed object store, and a browser cache all satisfy this shape. The backend owns durability, listing, and concurrency; the store owns framing, addressing, and verification.
A backend that returns the wrong bytes for a key is not trusted: `get` re-hashes what it reads and refuses to decode a mismatch.
The members are `get` and `set`, the vocabulary’s settled spellings for a keyed store’s read and write. `read` and `write` are reserved for a fixed-width field primitive.
## Properties
[Section titled “Properties”](#properties)
### has
[Section titled “has”](#has)
> `readonly` **has**: (`address`) => `Promise`<`boolean`>
Defined in: [packages/cas/src/artifact.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L39)
Whether `address` is present. O(1) expected for a map-backed backend.
#### Parameters
[Section titled “Parameters”](#parameters)
##### address
[Section titled “address”](#address)
`string`
#### Returns
[Section titled “Returns”](#returns)
`Promise`<`boolean`>
***
### set
[Section titled “set”](#set)
> `readonly` **set**: (`address`, `bytes`) => `Promise`<`void`>
Defined in: [packages/cas/src/artifact.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L48)
Store `bytes` under `address`, replacing whatever was there.
Content addressing makes a rewrite idempotent when the hash is deterministic, so a backend need not be idempotent itself: the store writes an address only when it read nothing back, or read back different bytes that it has already reported as a failure.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### address
[Section titled “address”](#address-1)
`string`
##### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`Promise`<`void`>
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`address`) => `Promise`<`Uint8Array`<`ArrayBufferLike`> | `undefined`>
Defined in: [packages/cas/src/artifact.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L50)
Return the bytes stored under `address`, or `undefined` when the address is absent.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### address
[Section titled “address”](#address-2)
`string`
#### Returns
[Section titled “Returns”](#returns-2)
`Promise`<`Uint8Array`<`ArrayBufferLike`> | `undefined`>
# ContentAddressedStore
Defined in: [packages/cas/src/artifact.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L54)
A store that names artifacts by the hash of their framing bytes.
## Properties
[Section titled “Properties”](#properties)
### addressOf
[Section titled “addressOf”](#addressof)
> `readonly` **addressOf**: (`artifact`) => `string`
Defined in: [packages/cas/src/artifact.ts:62](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L62)
Address the artifact would receive, without writing it. O(bytes); pure.
#### Parameters
[Section titled “Parameters”](#parameters)
##### artifact
[Section titled “artifact”](#artifact)
[`Artifact`](/reference/knotkit/cas/interfaces/artifact/)
#### Returns
[Section titled “Returns”](#returns)
`string`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARTIFACT` when the artifact cannot be framed, `INVALID_HASH` when the hash does not return an address-shaped string, or `HASH_FAILURE` when the hash throws.
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`artifact`) => `Promise`<`string`>
Defined in: [packages/cas/src/artifact.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L73)
Frame the artifact, then store it under its address unless the same bytes are already there. Returns the address. O(bytes).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### artifact
[Section titled “artifact”](#artifact-1)
[`Artifact`](/reference/knotkit/cas/interfaces/artifact/)
#### Returns
[Section titled “Returns”](#returns-1)
`Promise`<`string`>
#### Throws
[Section titled “Throws”](#throws-1)
As [addressOf](/reference/knotkit/cas/interfaces/contentaddressedstore/#addressof), plus `BACKEND_FAILURE` when the backend throws.
#### Throws
[Section titled “Throws”](#throws-2)
With `ADDRESS_COLLISION` when the address is present but holds different bytes, which means the injected hash mapped two artifacts to one address.
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`address`) => `Promise`<`boolean`>
Defined in: [packages/cas/src/artifact.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L80)
Whether `address` holds an artifact. O(1) expected, plus one validation.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### address
[Section titled “address”](#address)
`string`
#### Returns
[Section titled “Returns”](#returns-2)
`Promise`<`boolean`>
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_ADDRESS` when the address is not a safe storage key, or `BACKEND_FAILURE` when the backend throws.
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`address`) => `Promise`<[`WireEnvelope`](/reference/knotkit/wire/interfaces/wireenvelope/) | `undefined`>
Defined in: [packages/cas/src/artifact.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/artifact.ts#L95)
Read and verify the artifact stored under `address`, or `undefined` when the address is absent. O(bytes).
The bytes are re-hashed before decoding, so a backend that returned the wrong content, or a hash that stopped being deterministic, fails as `ADDRESS_MISMATCH` rather than as a payload that happens to decode.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### address
[Section titled “address”](#address-1)
`string`
#### Returns
[Section titled “Returns”](#returns-3)
`Promise`<[`WireEnvelope`](/reference/knotkit/wire/interfaces/wireenvelope/) | `undefined`>
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ADDRESS` when the address is not a safe storage key, or `BACKEND_FAILURE` when the backend throws.
#### Throws
[Section titled “Throws”](#throws-5)
With `ADDRESS_MISMATCH` when the stored bytes do not hash to their address, or with any `knotkit/wire` failure the envelope raises under this store’s magic.
# ContentAddressedStoreOptions
Defined in: [packages/cas/src/content-addressed-store.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/content-addressed-store.ts#L45)
Options for [contentAddressedStore](/reference/knotkit/cas/functions/contentaddressedstore/).
## Properties
[Section titled “Properties”](#properties)
### backend
[Section titled “backend”](#backend)
> `readonly` **backend**: [`ArtifactBackend`](/reference/knotkit/cas/interfaces/artifactbackend/)
Defined in: [packages/cas/src/content-addressed-store.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/content-addressed-store.ts#L47)
Where bytes are stored and read. The store never assumes it is local.
***
### hash
[Section titled “hash”](#hash)
> `readonly` **hash**: (`bytes`) => `string`
Defined in: [packages/cas/src/content-addressed-store.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/content-addressed-store.ts#L58)
Content hash from framed bytes to address. Injected, so a caller chooses the algorithm and its width, and so a test can use a hash that cannot collide.
It must be deterministic — two calls on equal bytes return one string — and collision-resistant enough for the store’s expected population. A 64-bit non-cryptographic hash is adequate below roughly 2^32 artifacts; above that, or against an adversary choosing the inputs, use SHA-256. A collision is not silent: see [ContentAddressedStore.add](/reference/knotkit/cas/interfaces/contentaddressedstore/#add).
#### Parameters
[Section titled “Parameters”](#parameters)
##### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`string`
***
### magic
[Section titled “magic”](#magic)
> `readonly` **magic**: `Uint8Array`
Defined in: [packages/cas/src/content-addressed-store.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/content-addressed-store.ts#L65)
The four-byte family marker this store accepts and writes. One store addresses one family of artifacts, so a `knotkit/heap` artifact read through a `knotkit/trie` store fails as `INVALID_MAGIC` rather than decoding under the wrong package’s rules.
# CasErrorCode
> **CasErrorCode** = [`CasInvalidInputErrorCode`](/reference/knotkit/cas/type-aliases/casinvalidinputerrorcode/) | [`CasParseErrorCode`](/reference/knotkit/cas/type-aliases/casparseerrorcode/)
Defined in: [packages/cas/src/errors.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L55)
A machine-readable code emitted by `knotkit/cas`.
# CasInvalidInputErrorCode
> **CasInvalidInputErrorCode** = *typeof* `invalidInputCodes`\[`number`]
Defined in: [packages/cas/src/errors.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L13)
A machine-readable caller-contract code emitted by `knotkit/cas`.
# CasParseErrorCode
> **CasParseErrorCode** = [`WireFailureCode`](/reference/knotkit/wire/type-aliases/wirefailurecode/) | *typeof* `casParseCodes`\[`number`]
Defined in: [packages/cas/src/errors.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L37)
A machine-readable parse code emitted by `knotkit/cas`.
# CAS_ERROR_CODES
> `const` **CAS_ERROR_CODES**: readonly [`CasErrorCode`](/reference/knotkit/cas/type-aliases/caserrorcode/)\[]
Defined in: [packages/cas/src/errors.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L58)
Every code emitted by `knotkit/cas`, in stable category order.
# CAS_INVALID_INPUT_ERROR_CODES
> `const` **CAS_INVALID_INPUT_ERROR_CODES**: `Readonly`<*typeof* `invalidInputCodes`>
Defined in: [packages/cas/src/errors.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L27)
Every caller-contract code this package throws.
`INVALID_ADDRESS` rejects an address that is not a safe storage key before a backend sees it. `INVALID_HASH` rejects a hash output that would not be one, which turns a misconfigured hash into a named failure instead of a store full of keys no other process can reproduce. `INVALID_ARTIFACT` covers an artifact `knotkit/wire` cannot frame. `HASH_FAILURE` and `BACKEND_FAILURE` cover an injected dependency that threw: the injection is part of the caller’s contract, so its failure is the caller’s to fix, and it must not escape as an anonymous exception from inside a library call.
# CAS_PARSE_ERROR_CODES
> `const` **CAS_PARSE_ERROR_CODES**: readonly [`CasParseErrorCode`](/reference/knotkit/cas/type-aliases/casparseerrorcode/)\[]
Defined in: [packages/cas/src/errors.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/cas/src/errors.ts#L49)
Every parse code this package throws.
Every shared wire-validation failure, plus the two failures only a content-addressed store can report: `ADDRESS_MISMATCH`, when the bytes read back do not hash to the address they were stored under, and `ADDRESS_COLLISION`, when they hash to it but are not the artifact that was asked to be stored. Both mean the store cannot vouch for the content, which is the one promise this package makes.
# knotkit/combinatorics
## Classes
[Section titled “Classes”](#classes)
* [CombinatoricsInvalidInputError](/reference/knotkit/combinatorics/classes/combinatoricsinvalidinputerror/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [CombinatoricsInvalidInputErrorCode](/reference/knotkit/combinatorics/type-aliases/combinatoricsinvalidinputerrorcode/)
* [CombinatoricsErrorCode](/reference/knotkit/combinatorics/type-aliases/combinatoricserrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [COMBINATORICS_INVALID_INPUT_ERROR_CODES](/reference/knotkit/combinatorics/variables/combinatorics_invalid_input_error_codes/)
* [COMBINATORICS_ERROR_CODES](/reference/knotkit/combinatorics/variables/combinatorics_error_codes/)
* [COMBINATORICS_MAX_COUNT](/reference/knotkit/combinatorics/variables/combinatorics_max_count/)
## Functions
[Section titled “Functions”](#functions)
* [bellNumber](/reference/knotkit/combinatorics/functions/bellnumber/)
* [logBellNumber](/reference/knotkit/combinatorics/functions/logbellnumber/)
* [binomialCoefficient](/reference/knotkit/combinatorics/functions/binomialcoefficient/)
* [logBinomialCoefficient](/reference/knotkit/combinatorics/functions/logbinomialcoefficient/)
* [factorial](/reference/knotkit/combinatorics/functions/factorial/)
* [logFactorial](/reference/knotkit/combinatorics/functions/logfactorial/)
* [stirlingFirstKind](/reference/knotkit/combinatorics/functions/stirlingfirstkind/)
* [stirlingFirstKindRow](/reference/knotkit/combinatorics/functions/stirlingfirstkindrow/)
* [logStirlingFirstKind](/reference/knotkit/combinatorics/functions/logstirlingfirstkind/)
* [stirlingSecondKind](/reference/knotkit/combinatorics/functions/stirlingsecondkind/)
* [stirlingSecondKindRow](/reference/knotkit/combinatorics/functions/stirlingsecondkindrow/)
* [logStirlingSecondKind](/reference/knotkit/combinatorics/functions/logstirlingsecondkind/)
# CombinatoricsInvalidInputError
Defined in: [packages/combinatorics/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L17)
Thrown when a count is outside the supported domain.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`CombinatoricsInvalidInputErrorCode`](/reference/knotkit/combinatorics/type-aliases/combinatoricsinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new CombinatoricsInvalidInputError**(`code`, `message`): `CombinatoricsInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_COUNT"` | `"COUNT_TOO_LARGE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`CombinatoricsInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/combinatorics"`
Defined in: [packages/combinatorics/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L18)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_COUNT"` | `"COUNT_TOO_LARGE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# bellNumber
> **bellNumber**(`n`): `bigint`
Defined in: [packages/combinatorics/src/bell-number.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/bell-number.ts#L12)
Count all set partitions of n items as a bigint, with bellNumber(0) = 1n.
O(n²) additions and O(n) bigint storage.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# binomialCoefficient
> **binomialCoefficient**(`n`, `k`): `bigint`
Defined in: [packages/combinatorics/src/binomial-coefficient.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/binomial-coefficient.ts#L26)
Count the combinations of k from n items as a bigint. Returns 0n for k > n.
O(min(k, n - k)) arithmetic operations when k <= n.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# factorial
> **factorial**(`n`): `bigint`
Defined in: [packages/combinatorics/src/factorial.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/factorial.ts#L41)
Count permutations of n items as a bigint, with factorial(0) = 1n.
O(n) multiplications.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# logBellNumber
> **logBellNumber**(`n`): `number`
Defined in: [packages/combinatorics/src/bell-number.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/bell-number.ts#L39)
Take the natural logarithm of the number of set partitions of n items.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# logBinomialCoefficient
> **logBinomialCoefficient**(`n`, `k`): `number`
Defined in: [packages/combinatorics/src/binomial-coefficient.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/binomial-coefficient.ts#L41)
Take the natural logarithm of the number of combinations of k from n items for any non-negative safe integer counts. Returns -Infinity for k > n.
O(1) time. Evaluates the logarithmic ratio without subtracting two large log-factorials.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count.
# logFactorial
> **logFactorial**(`n`): `number`
Defined in: [packages/combinatorics/src/factorial.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/factorial.ts#L53)
Take the natural logarithm of n! for any non-negative safe integer n.
O(1) time, using a once-built table of exact log-factorials up to 170 and a Stirling expansion thereafter.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count.
# logStirlingFirstKind
> **logStirlingFirstKind**(`n`, `k`): `number`
Defined in: [packages/combinatorics/src/stirling-first-kind.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-first-kind.ts#L39)
Take the natural logarithm of the unsigned first-kind count. Returns -Infinity for a zero count.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# logStirlingSecondKind
> **logStirlingSecondKind**(`n`, `k`): `number`
Defined in: [packages/combinatorics/src/stirling-second-kind.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-second-kind.ts#L38)
Take the natural logarithm of the second-kind count. Returns -Infinity for a zero count.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# stirlingFirstKind
> **stirlingFirstKind**(`n`, `k`): `bigint`
Defined in: [packages/combinatorics/src/stirling-first-kind.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-first-kind.ts#L17)
Count permutations of n items with k cycles, the unsigned Stirling number of the first kind, as a bigint. Returns 0n for k > n.
O(nk) arithmetic operations and O(k) bigint storage when k <= n.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# stirlingFirstKindRow
> **stirlingFirstKindRow**(`n`): readonly `bigint`\[]
Defined in: [packages/combinatorics/src/stirling-first-kind.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-first-kind.ts#L29)
Return the unsigned Stirling numbers of the first kind for k from 0 to n, in order.
O(n²) arithmetic operations and O(n) bigint storage.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `bigint`\[]
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# stirlingSecondKind
> **stirlingSecondKind**(`n`, `k`): `bigint`
Defined in: [packages/combinatorics/src/stirling-second-kind.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-second-kind.ts#L16)
Count partitions of n items into k non-empty blocks as a bigint. Returns 0n for k > n.
O(nk) arithmetic operations and O(k) bigint storage when k <= n.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
### k
[Section titled “k”](#k)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# stirlingSecondKindRow
> **stirlingSecondKindRow**(`n`): readonly `bigint`\[]
Defined in: [packages/combinatorics/src/stirling-second-kind.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/stirling-second-kind.ts#L28)
Return the Stirling numbers of the second kind for k from 0 to n, in order.
O(n²) arithmetic operations and O(n) bigint storage.
## Parameters
[Section titled “Parameters”](#parameters)
### n
[Section titled “n”](#n)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `bigint`\[]
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or `COUNT_TOO_LARGE` if n exceeds `COMBINATORICS_MAX_COUNT`.
# CombinatoricsErrorCode
> **CombinatoricsErrorCode** = [`CombinatoricsInvalidInputErrorCode`](/reference/knotkit/combinatorics/type-aliases/combinatoricsinvalidinputerrorcode/)
Defined in: [packages/combinatorics/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L14)
A machine-readable error code emitted by `knotkit/combinatorics`.
# CombinatoricsInvalidInputErrorCode
> **CombinatoricsInvalidInputErrorCode** = *typeof* [`COMBINATORICS_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/combinatorics/variables/combinatorics_invalid_input_error_codes/)\[`number`]
Defined in: [packages/combinatorics/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L11)
A machine-readable invalid-input code emitted by `knotkit/combinatorics`.
# COMBINATORICS_ERROR_CODES
> `const` **COMBINATORICS_ERROR_CODES**: *typeof* [`COMBINATORICS_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/combinatorics/variables/combinatorics_invalid_input_error_codes/) = `COMBINATORICS_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/combinatorics/src/errors.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L7)
Every machine-readable error code emitted by `knotkit/combinatorics`.
# COMBINATORICS_INVALID_INPUT_ERROR_CODES
> `const` **COMBINATORICS_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_COUNT"`, `"COUNT_TOO_LARGE"`]
Defined in: [packages/combinatorics/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/errors.ts#L4)
Machine-readable input errors emitted by `knotkit/combinatorics`.
# COMBINATORICS_MAX_COUNT
> `const` **COMBINATORICS_MAX_COUNT**: `2048` = `2048`
Defined in: [packages/combinatorics/src/internal/validation.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/combinatorics/src/internal/validation.ts#L4)
Largest item count for the exact functions and the Stirling and Bell logarithms.
# knotkit/deque
## Classes
[Section titled “Classes”](#classes)
* [DequeInvalidInputError](/reference/knotkit/deque/classes/dequeinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [DequeOptions](/reference/knotkit/deque/interfaces/dequeoptions/)
* [Deque](/reference/knotkit/deque/interfaces/deque/)
* [DequeFactory](/reference/knotkit/deque/interfaces/dequefactory/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [DequeKind](/reference/knotkit/deque/type-aliases/dequekind/)
* [DequeInvalidInputErrorCode](/reference/knotkit/deque/type-aliases/dequeinvalidinputerrorcode/)
* [DequeErrorCode](/reference/knotkit/deque/type-aliases/dequeerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [DEQUE_KINDS](/reference/knotkit/deque/variables/deque_kinds/)
* [DEQUE_MAX_CAPACITY](/reference/knotkit/deque/variables/deque_max_capacity/)
* [DEQUE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/deque/variables/deque_invalid_input_error_codes/)
* [DEQUE_ERROR_CODES](/reference/knotkit/deque/variables/deque_error_codes/)
* [\_\_DEQUE_LAYOUTS](/reference/knotkit/deque/variables/deque_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [arrayDeque](/reference/knotkit/deque/functions/arraydeque/)
* [float64ArrayDeque](/reference/knotkit/deque/functions/float64arraydeque/)
# DequeInvalidInputError
Defined in: [packages/deque/src/errors.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L28)
Thrown when a deque is constructed with a capacity it cannot keep, when a value, index, or read at an empty end breaks the deque’s contract, when it would grow past the size it can hold, or when an iterator is stepped after the deque changed under it.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`DequeInvalidInputErrorCode`](/reference/knotkit/deque/type-aliases/dequeinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new DequeInvalidInputError**(`code`, `message`): `DequeInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_INDEX"` | `"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"INVALID_CAPACITY"` | `"INVALID_VALUE"` | `"EMPTY"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`DequeInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/deque"`
Defined in: [packages/deque/src/errors.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L29)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_INDEX"` | `"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"INVALID_CAPACITY"` | `"INVALID_VALUE"` | `"EMPTY"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# arrayDeque
> **arrayDeque**<`A`>(`options?`): [`Deque`](/reference/knotkit/deque/interfaces/deque/)<`A`>
Defined in: [packages/deque/src/array-deque.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/array-deque.ts#L52)
Create a [Deque](/reference/knotkit/deque/interfaces/deque/) over a plain array ring buffer, for elements of any type except `undefined`. The type parameter excludes `undefined`, so `arrayDeque()` fails to compile; store `null`, or a sentinel of your own, for a missing value.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A` *extends* { } | `null`
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`DequeOptions`](/reference/knotkit/deque/interfaces/dequeoptions/)<`A`> = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Deque`](/reference/knotkit/deque/interfaces/deque/)<`A`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not `Infinity` or a positive safe integer no larger than `DEQUE_MAX_CAPACITY` (`Infinity` is accepted), `INVALID_VALUE` when `options.items` holds `undefined`, or `MAX_CAPACITY_EXCEEDED` when `options.items` holds more elements than the layout can store.
# float64ArrayDeque
> **float64ArrayDeque**(`options?`): [`Deque`](/reference/knotkit/deque/interfaces/deque/)<`number`>
Defined in: [packages/deque/src/float64-array-deque.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/float64-array-deque.ts#L31)
Create a [Deque](/reference/knotkit/deque/interfaces/deque/) of numbers over a `Float64Array` ring buffer: eight bytes per slot and no per-element allocation. `NaN` and `-0` are stored as given.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`DequeOptions`](/reference/knotkit/deque/interfaces/dequeoptions/)<`number`> = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Deque`](/reference/knotkit/deque/interfaces/deque/)<`number`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not `Infinity` or a positive safe integer no larger than `DEQUE_MAX_CAPACITY` (`Infinity` is accepted), `INVALID_VALUE` when `options.items` holds anything but numbers, or `MAX_CAPACITY_EXCEEDED` when `options.items` holds more elements than the runtime will allocate storage for.
# Deque
Defined in: [packages/deque/src/deque.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L37)
A double-ended queue over a ring buffer: O(1) amortized pushes and O(1) pops, peeks, and index reads at both ends.
The front is where iteration starts. `undefined` is not a storable value, so a push returning `undefined` always means nothing was evicted.
The type parameter is invariant: a mutable deque both consumes and produces `A`. Every callable member is declared in property syntax so `strictFunctionTypes` keeps the parameters contravariant; method-syntax parameters would compare bivariantly and let `Deque` widen into `Deque`, defeating the invariance `in out` exists to enforce.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"array"` | `"float64-array"`
Defined in: [packages/deque/src/deque.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L39)
The storage this deque uses: `'array'` or `'float64-array'`.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/deque/src/deque.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L41)
Number of elements held. O(1). The deque is empty when this is `0`.
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/deque/src/deque.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L43)
The most elements the deque holds before a push evicts; `Infinity` when it grows without bound.
***
### pushBack
[Section titled “pushBack”](#pushback)
> `readonly` **pushBack**: (`value`) => `A` | `undefined`
Defined in: [packages/deque/src/deque.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L54)
Add an element at the back. O(1) amortized.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`A`
#### Returns
[Section titled “Returns”](#returns)
`A` | `undefined`
The element evicted from the front when the deque was at capacity; otherwise `undefined`.
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VALUE` when the layout cannot store the value, or `MAX_CAPACITY_EXCEEDED` when growing would pass [DEQUE_MAX_CAPACITY](/reference/knotkit/deque/variables/deque_max_capacity/) or the runtime refuses the allocation. The deque is unchanged after either.
***
### pushFront
[Section titled “pushFront”](#pushfront)
> `readonly` **pushFront**: (`value`) => `A` | `undefined`
Defined in: [packages/deque/src/deque.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L63)
Add an element at the front. O(1) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`A`
#### Returns
[Section titled “Returns”](#returns-1)
`A` | `undefined`
The element evicted from the back when the deque was at capacity; otherwise `undefined`.
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_VALUE` or `MAX_CAPACITY_EXCEEDED`, as [pushBack](/reference/knotkit/deque/interfaces/deque/#pushback) does.
***
### popBack
[Section titled “popBack”](#popback)
> `readonly` **popBack**: () => `A`
Defined in: [packages/deque/src/deque.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L69)
Remove and return the element at the back. O(1).
#### Returns
[Section titled “Returns”](#returns-2)
`A`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the deque is empty.
***
### popFront
[Section titled “popFront”](#popfront)
> `readonly` **popFront**: () => `A`
Defined in: [packages/deque/src/deque.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L75)
Remove and return the element at the front. O(1).
#### Returns
[Section titled “Returns”](#returns-3)
`A`
#### Throws
[Section titled “Throws”](#throws-3)
With code `EMPTY` when the deque is empty.
***
### peekBack
[Section titled “peekBack”](#peekback)
> `readonly` **peekBack**: () => `A`
Defined in: [packages/deque/src/deque.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L81)
Return the element at the back without removing it. O(1).
#### Returns
[Section titled “Returns”](#returns-4)
`A`
#### Throws
[Section titled “Throws”](#throws-4)
With code `EMPTY` when the deque is empty.
***
### peekFront
[Section titled “peekFront”](#peekfront)
> `readonly` **peekFront**: () => `A`
Defined in: [packages/deque/src/deque.ts:87](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L87)
Return the element at the front without removing it. O(1).
#### Returns
[Section titled “Returns”](#returns-5)
`A`
#### Throws
[Section titled “Throws”](#throws-5)
With code `EMPTY` when the deque is empty.
***
### at
[Section titled “at”](#at)
> `readonly` **at**: (`index`) => `A`
Defined in: [packages/deque/src/deque.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L95)
Return the element at `index`, counted from the front for `0 <= index < size` and from the back for `-size <= index < 0`. O(1).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### index
[Section titled “index”](#index)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`A`
#### Throws
[Section titled “Throws”](#throws-6)
With code `INVALID_INDEX` when `index` is not an integer or falls outside that range.
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/deque/src/deque.ts:97](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L97)
Remove every element and release the storage that held them. O(1). Keeps [capacity](/reference/knotkit/deque/interfaces/deque/#capacity).
#### Returns
[Section titled “Returns”](#returns-7)
`void`
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`A`>
Defined in: [packages/deque/src/deque.ts:105](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L105)
Iterate over every element from front to back, lazily. O(1) per step.
#### Returns
[Section titled “Returns”](#returns-8)
`IterableIterator`<`A`>
#### Throws
[Section titled “Throws”](#throws-7)
With code `MODIFIED_DURING_ITERATION` from a step taken after the deque was pushed to, popped from, or cleared since this call returned. An iterator that has finished stays finished.
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<`A`>
Defined in: [packages/deque/src/deque.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L107)
The same function as [values](/reference/knotkit/deque/interfaces/deque/#values), so `for (const value of deque)` works.
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`<`A`>
# DequeFactory
Defined in: [packages/deque/src/deque.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L130)
The signature every layout fits once its elements are numbers.
`float64ArrayDeque` stores numbers only, so the one signature both layouts share is the number one: `arrayDeque` fits it at `A = number`. That keeps a single table a test, benchmark, or caller can sweep.
> **DequeFactory**(`options?`): [`Deque`](/reference/knotkit/deque/interfaces/deque/)<`number`>
Defined in: [packages/deque/src/deque.ts:131](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L131)
The signature every layout fits once its elements are numbers.
`float64ArrayDeque` stores numbers only, so the one signature both layouts share is the number one: `arrayDeque` fits it at `A = number`. That keeps a single table a test, benchmark, or caller can sweep.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`DequeOptions`](/reference/knotkit/deque/interfaces/dequeoptions/)<`number`>
## Returns
[Section titled “Returns”](#returns)
[`Deque`](/reference/knotkit/deque/interfaces/deque/)<`number`>
# DequeOptions
Defined in: [packages/deque/src/deque.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L7)
The options every deque factory accepts, whatever its storage.
The record is the same for every layout, so a caller can switch layout by changing the factory alone.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### items?
[Section titled “items?”](#items)
> `readonly` `optional` **items?**: `Iterable`<`A`, `any`, `any`>
Defined in: [packages/deque/src/deque.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L13)
Elements to push at the back, in iteration order, as the deque is built. With [capacity](/reference/knotkit/deque/interfaces/dequeoptions/#capacity), only the last `capacity` of them remain, as if each had been pushed in turn.
***
### capacity?
[Section titled “capacity?”](#capacity)
> `readonly` `optional` **capacity?**: `number`
Defined in: [packages/deque/src/deque.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L21)
The most elements the deque holds. A push onto a full deque evicts the element at the opposite end and returns it, which makes a bounded deque a sliding window. Must be `Infinity` or a positive safe integer no larger than [DEQUE_MAX_CAPACITY](/reference/knotkit/deque/variables/deque_max_capacity/). Omit it, or pass `Infinity`, for a deque that grows without bound; that is the value [Deque.capacity](/reference/knotkit/deque/interfaces/deque/#capacity) reports.
# DequeErrorCode
> **DequeErrorCode** = [`DequeInvalidInputErrorCode`](/reference/knotkit/deque/type-aliases/dequeinvalidinputerrorcode/)
Defined in: [packages/deque/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L20)
A machine-readable error code emitted by `knotkit/deque`.
# DequeInvalidInputErrorCode
> **DequeInvalidInputErrorCode** = *typeof* [`DEQUE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/deque/variables/deque_invalid_input_error_codes/)\[`number`]
Defined in: [packages/deque/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L17)
A machine-readable invalid-input code emitted by `knotkit/deque`.
# DequeKind
> **DequeKind** = *typeof* [`DEQUE_KINDS`](/reference/knotkit/deque/variables/deque_kinds/)\[`number`]
Defined in: [packages/deque/src/deque.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L121)
Storage layouts of the deque factories.
# DEQUE_ERROR_CODES
> `const` **DEQUE_ERROR_CODES**: *typeof* [`DEQUE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/deque/variables/deque_invalid_input_error_codes/) = `DEQUE_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/deque/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L14)
Every machine-readable error code emitted by `knotkit/deque`.
# DEQUE_INVALID_INPUT_ERROR_CODES
> `const` **DEQUE_INVALID_INPUT_ERROR_CODES**: readonly \[`"EMPTY"`, `"INVALID_CAPACITY"`, `"INVALID_VALUE"`, `"INVALID_INDEX"`, `"MAX_CAPACITY_EXCEEDED"`, `"MODIFIED_DURING_ITERATION"`]
Defined in: [packages/deque/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/deque`.
# DEQUE_KINDS
> `const` **DEQUE_KINDS**: readonly \[`"array"`, `"float64-array"`]
Defined in: [packages/deque/src/deque.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L118)
Every storage layout this package provides, as a runtime value.
Exported so a caller can enumerate the layouts exhaustively without restating them, and so [DequeKind](/reference/knotkit/deque/type-aliases/dequekind/) is derived from the list rather than duplicating it. `__DEQUE_LAYOUTS` in `layouts.ts` is the matching construction table.
# __DEQUE_LAYOUTS
> `const` **\_\_DEQUE_LAYOUTS**: `Readonly`<`Record`<[`DequeKind`](/reference/knotkit/deque/type-aliases/dequekind/), [`DequeFactory`](/reference/knotkit/deque/interfaces/dequefactory/)>>
Defined in: [packages/deque/src/layouts.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/layouts.ts#L14)
Every deque layout, keyed by the `kind` a deque built from it reports.
Iterate this table instead of naming factories one by one: a property sweep, a benchmark, or a caller comparing layouts covers every entry, and a layout added to `DEQUE_KINDS` fails to typecheck until it is enrolled here too. The table’s signature is the one both layouts share, over number elements; call `arrayDeque` directly for any other element type.
# DEQUE_MAX_CAPACITY
> `const` **DEQUE_MAX_CAPACITY**: `number`
Defined in: [packages/deque/src/deque.ts:144](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/deque/src/deque.ts#L144)
The most elements a deque can hold: `2 ** 30`. Storage is a power-of-two ring, and this bound keeps every wrapped index a non-negative 32-bit integer.
It is an upper bound, not a promise: a runtime may refuse to allocate storage this large, as Bun does for a `Float64Array` of `2 ** 30` elements, and a push then throws `MAX_CAPACITY_EXCEEDED`. `arrayDeque` stops at `2 ** 25` elements for the same reason.
# knotkit/disjoint-set
## Classes
[Section titled “Classes”](#classes)
* [DisjointSetParseError](/reference/knotkit/disjoint-set/classes/disjointsetparseerror/)
* [DisjointSetInvalidInputError](/reference/knotkit/disjoint-set/classes/disjointsetinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [DisjointSet](/reference/knotkit/disjoint-set/interfaces/disjointset/)
* [GrowableDisjointSet](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)
* [IndexedDisjointSet](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [DisjointSetKind](/reference/knotkit/disjoint-set/type-aliases/disjointsetkind/)
* [GrowableDisjointSetKind](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetkind/)
* [GrowableDisjointSetFactory](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
* [DisjointSetInvalidInputErrorCode](/reference/knotkit/disjoint-set/type-aliases/disjointsetinvalidinputerrorcode/)
* [DisjointSetParseErrorCode](/reference/knotkit/disjoint-set/type-aliases/disjointsetparseerrorcode/)
* [DisjointSetErrorCode](/reference/knotkit/disjoint-set/type-aliases/disjointseterrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [DISJOINT_SET_KINDS](/reference/knotkit/disjoint-set/variables/disjoint_set_kinds/)
* [GROWABLE_DISJOINT_SET_KINDS](/reference/knotkit/disjoint-set/variables/growable_disjoint_set_kinds/)
* [DISJOINT_SET_INVALID_INPUT_ERROR_CODES](/reference/knotkit/disjoint-set/variables/disjoint_set_invalid_input_error_codes/)
* [DISJOINT_SET_PARSE_ERROR_CODES](/reference/knotkit/disjoint-set/variables/disjoint_set_parse_error_codes/)
* [DISJOINT_SET_ERROR_CODES](/reference/knotkit/disjoint-set/variables/disjoint_set_error_codes/)
* [\_\_GROWABLE_DISJOINT_SET_LAYOUTS](/reference/knotkit/disjoint-set/variables/growable_disjoint_set_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [objectDisjointSet](/reference/knotkit/disjoint-set/functions/objectdisjointset/)
* [indexedDisjointSet](/reference/knotkit/disjoint-set/functions/indexeddisjointset/)
* [structOfArraysDisjointSet](/reference/knotkit/disjoint-set/functions/structofarraysdisjointset/)
# DisjointSetInvalidInputError
Defined in: [packages/disjoint-set/src/errors.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L63)
Thrown when a caller passes an element or size that violates a `DisjointSet`’s public contract.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`DisjointSetInvalidInputErrorCode`](/reference/knotkit/disjoint-set/type-aliases/disjointsetinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new DisjointSetInvalidInputError**(`code`, `message`): `DisjointSetInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"ELEMENT_NOT_FOUND"` | `"ELEMENT_ALREADY_REGISTERED"` | `"SIZE_OUT_OF_RANGE"` | `"MAX_SIZE_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`DisjointSetInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/disjoint-set"`
Defined in: [packages/disjoint-set/src/errors.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L64)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"ELEMENT_NOT_FOUND"` | `"ELEMENT_ALREADY_REGISTERED"` | `"SIZE_OUT_OF_RANGE"` | `"MAX_SIZE_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# DisjointSetParseError
Defined in: [packages/disjoint-set/src/errors.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L58)
Thrown when decoding a `SerializedDisjointSet` that is malformed or fails validation.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`DisjointSetParseErrorCode`](/reference/knotkit/disjoint-set/type-aliases/disjointsetparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new DisjointSetParseError**(`code`, `message`): `DisjointSetParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"MISSING_ELEMENTS"` | `"INVALID_LABELS"` | `"INVALID_INDEXED_ELEMENT"` | `"INVALID_ELEMENT"` | `"ELEMENTS_LABELS_LENGTH_MISMATCH"` | `"DUPLICATE_ELEMENT"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`DisjointSetParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/disjoint-set"`
Defined in: [packages/disjoint-set/src/errors.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L59)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"MISSING_ELEMENTS"` | `"INVALID_LABELS"` | `"INVALID_INDEXED_ELEMENT"` | `"INVALID_ELEMENT"` | `"ELEMENTS_LABELS_LENGTH_MISMATCH"` | `"DUPLICATE_ELEMENT"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
# indexedDisjointSet
> **indexedDisjointSet**(`size`): [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
Defined in: [packages/disjoint-set/src/indexed-disjoint-set.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/indexed-disjoint-set.ts#L40)
Create a disjoint set over the dense integer range `0..size - 1`.
Parent pointers and ranks are stored directly in typed arrays, with no element-to-index `Map` or element array. Calling `append` adds and returns the next dense index.
## Parameters
[Section titled “Parameters”](#parameters)
### size
[Section titled “size”](#size)
`number`
Initial number of elements.
## Returns
[Section titled “Returns”](#returns)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
## Throws
[Section titled “Throws”](#throws)
When `size` is not a safe integer in the supported `Int32Array` index range.
# objectDisjointSet
> **objectDisjointSet**<`T`>(`elements?`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:167](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L167)
Create a [DisjointSet](/reference/knotkit/disjoint-set/interfaces/disjointset/) backed by one `{ parent, rank }` object per element, optionally pre-populated with elements that each start in their own singleton set.
Merges follow union by rank. The shorter tree is attached under the taller one, so tree height grows only when two trees of equal rank meet. Lookups follow path halving, a single-pass compression that repoints every node it visits to its grandparent and then continues from that grandparent. Together they bound each operation at O(alpha(n)) amortized time.
Prefer [indexedDisjointSet](/reference/knotkit/disjoint-set/functions/indexeddisjointset/) when elements are the dense integer range `0..size - 1`, or [structOfArraysDisjointSet](/reference/knotkit/disjoint-set/functions/structofarraysdisjointset/) for large generic element counts.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### elements?
[Section titled “elements?”](#elements)
`Iterable`<`T`, `any`, `any`>
Elements to insert, each in its own singleton set.
## Returns
[Section titled “Returns”](#returns)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
## Throws
[Section titled “Throws”](#throws)
When `elements` yields the same element twice.
# structOfArraysDisjointSet
> **structOfArraysDisjointSet**<`T`>(`elements?`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/struct-of-arrays-disjoint-set.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/struct-of-arrays-disjoint-set.ts#L57)
Create a [DisjointSet](/reference/knotkit/disjoint-set/interfaces/disjointset/) backed by a struct of arrays. Parent pointers live in an `Int32Array` and ranks in a `Uint8Array`, instead of one `{ parent, rank }` object per element.
The algorithm is the one [objectDisjointSet](/reference/knotkit/disjoint-set/functions/objectdisjointset/) uses, union by rank with path halving, and the observable behavior is identical. Only the memory layout differs, with two consequences at scale:
* **Node memory.** A `{ parent, rank }` object plus its slot in the backing array measured 48 bytes per element in a prior V8 run (arm64), once the object header, the hidden-class pointer, and alignment are counted. The typed arrays cost exactly 5 bytes per element, so node storage shrinks by about 9x. Both generic layouts additionally keep the same element registry. Use [indexedDisjointSet](/reference/knotkit/disjoint-set/functions/indexeddisjointset/) to remove that registry for dense integer IDs.
* **Locality.** Parent pointers sit in one contiguous buffer, so the pointer chase inside `find` walks cache lines instead of scattered heap objects, and each read compiles to an indexed load rather than a property lookup.
A `Uint8Array` is wide enough for ranks. Union by rank keeps rank bounded by the height of the tree, which is at most log2(n), so 255 covers every element count an `Int32Array` can index.
The typed arrays double in capacity when they fill up, which makes `add` amortized O(1) and leaves at most 2x the needed capacity allocated.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### elements?
[Section titled “elements?”](#elements)
`Iterable`<`T`, `any`, `any`>
Elements to insert, each in its own singleton set.
## Returns
[Section titled “Returns”](#returns)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
## Throws
[Section titled “Throws”](#throws)
When `elements` yields the same element twice.
# DisjointSet
Defined in: [packages/disjoint-set/src/disjoint-set.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L51)
A collection of elements partitioned into disjoint sets, also known as union-find.
Every element belongs to exactly one set, and each set is identified by one of its members, its representative. Two elements are connected when they resolve to the same representative. Which member acts as the representative is an implementation detail. It can change after any `unite` call, so treat it as a comparable token rather than a stable identity.
Elements are compared with `SameValueZero`, the same equality that `Map` and `Set` use. `NaN` equals itself, and `0` equals `-0`.
All implementations mutate in place. Complexities below are stated for `n` elements. `alpha` is the inverse Ackermann function, which stays below 5 for every practical input size, so the amortized bounds are constant in practice.
The type parameter is invariant: a mutable container both consumes and produces `T`. Every callable member is declared in property syntax so `strictFunctionTypes` keeps the parameters that mention `T` contravariant; method-syntax parameters would compare bivariantly and let `DisjointSet` widen into `DisjointSet`, defeating the invariance `in out T` exists to enforce. The members whose parameters mention `T` in neither position follow the same syntax so the interface reads uniformly.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)
* [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"object"` | `"indexed"` | `"struct-of-arrays"`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L53)
Stable identifier for the implementation’s storage layout.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L55)
Number of elements across all sets. O(1).
***
### setCount
[Section titled “setCount”](#setcount)
> `readonly` **setCount**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L57)
Number of disjoint sets. O(1).
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`element`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L59)
Return `true` when the element belongs to the disjoint set. O(1) average.
#### Parameters
[Section titled “Parameters”](#parameters)
##### element
[Section titled “element”](#element)
`T`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
***
### unite
[Section titled “unite”](#unite)
> `readonly` **unite**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L67)
Merge the sets containing `x` and `y`. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`T`
##### y
[Section titled “y”](#y)
`T`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
`true` when two distinct sets were merged, `false` when both elements already belonged to the same set.
#### Throws
[Section titled “Throws”](#throws)
When either element is absent.
***
### areConnected
[Section titled “areConnected”](#areconnected)
> `readonly` **areConnected**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L74)
Return `true` when `x` and `y` belong to the same set. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`T`
##### y
[Section titled “y”](#y-1)
`T`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
#### Throws
[Section titled “Throws”](#throws-1)
When either element is absent.
***
### find
[Section titled “find”](#find)
> `readonly` **find**: (`element`) => `T`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L81)
Return the representative of the set containing the element. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### element
[Section titled “element”](#element-1)
`T`
#### Returns
[Section titled “Returns”](#returns-3)
`T`
#### Throws
[Section titled “Throws”](#throws-2)
When the element is absent.
***
### elements
[Section titled “elements”](#elements)
> `readonly` **elements**: () => `IterableIterator`<`T`>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L88)
Iterate over every element in insertion order. O(1) per step, O(n) total.
The iterator covers the elements present when the call was made, so adding elements while iterating does not extend the walk.
#### Returns
[Section titled “Returns”](#returns-4)
`IterableIterator`<`T`>
***
### sets
[Section titled “sets”](#sets)
> `readonly` **sets**: () => `Map`<`T`, `T`\[]>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:94](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L94)
Collect every set into a `Map` keyed by representative. Members appear in insertion order. O(n \* alpha(n)) time and O(n) space. The result is a copy and does not track later mutations.
#### Returns
[Section titled “Returns”](#returns-5)
`Map`<`T`, `T`\[]>
# GrowableDisjointSet
Defined in: [packages/disjoint-set/src/disjoint-set.ts:98](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L98)
A disjoint set whose element domain can grow after construction.
## Extends
[Section titled “Extends”](#extends)
* [`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/)<`T`>
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L55)
Number of elements across all sets. O(1).
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`size`](/reference/knotkit/disjoint-set/interfaces/disjointset/#size)
***
### setCount
[Section titled “setCount”](#setcount)
> `readonly` **setCount**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L57)
Number of disjoint sets. O(1).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`setCount`](/reference/knotkit/disjoint-set/interfaces/disjointset/#setcount)
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`element`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L59)
Return `true` when the element belongs to the disjoint set. O(1) average.
#### Parameters
[Section titled “Parameters”](#parameters)
##### element
[Section titled “element”](#element)
`T`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`has`](/reference/knotkit/disjoint-set/interfaces/disjointset/#has)
***
### unite
[Section titled “unite”](#unite)
> `readonly` **unite**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L67)
Merge the sets containing `x` and `y`. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`T`
##### y
[Section titled “y”](#y)
`T`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
`true` when two distinct sets were merged, `false` when both elements already belonged to the same set.
#### Throws
[Section titled “Throws”](#throws)
When either element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`unite`](/reference/knotkit/disjoint-set/interfaces/disjointset/#unite)
***
### areConnected
[Section titled “areConnected”](#areconnected)
> `readonly` **areConnected**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L74)
Return `true` when `x` and `y` belong to the same set. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`T`
##### y
[Section titled “y”](#y-1)
`T`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
#### Throws
[Section titled “Throws”](#throws-1)
When either element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`areConnected`](/reference/knotkit/disjoint-set/interfaces/disjointset/#areconnected)
***
### find
[Section titled “find”](#find)
> `readonly` **find**: (`element`) => `T`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L81)
Return the representative of the set containing the element. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### element
[Section titled “element”](#element-1)
`T`
#### Returns
[Section titled “Returns”](#returns-3)
`T`
#### Throws
[Section titled “Throws”](#throws-2)
When the element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`find`](/reference/knotkit/disjoint-set/interfaces/disjointset/#find)
***
### elements
[Section titled “elements”](#elements)
> `readonly` **elements**: () => `IterableIterator`<`T`>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L88)
Iterate over every element in insertion order. O(1) per step, O(n) total.
The iterator covers the elements present when the call was made, so adding elements while iterating does not extend the walk.
#### Returns
[Section titled “Returns”](#returns-4)
`IterableIterator`<`T`>
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`elements`](/reference/knotkit/disjoint-set/interfaces/disjointset/#elements)
***
### sets
[Section titled “sets”](#sets)
> `readonly` **sets**: () => `Map`<`T`, `T`\[]>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:94](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L94)
Collect every set into a `Map` keyed by representative. Members appear in insertion order. O(n \* alpha(n)) time and O(n) space. The result is a copy and does not track later mutations.
#### Returns
[Section titled “Returns”](#returns-5)
`Map`<`T`, `T`\[]>
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`sets`](/reference/knotkit/disjoint-set/interfaces/disjointset/#sets)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"object"` | `"struct-of-arrays"`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:100](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L100)
Generic growable layouts use object or struct-of-arrays storage.
#### Overrides
[Section titled “Overrides”](#overrides)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`kind`](/reference/knotkit/disjoint-set/interfaces/disjointset/#kind)
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`element`) => `void`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L107)
Add an element as its own singleton set. O(1) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### element
[Section titled “element”](#element-2)
`T`
#### Returns
[Section titled “Returns”](#returns-6)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With code `ELEMENT_ALREADY_REGISTERED` when the element is already present.
# IndexedDisjointSet
Defined in: [packages/disjoint-set/src/indexed-disjoint-set.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/indexed-disjoint-set.ts#L8)
A dense integer disjoint set that can append the next index.
## Extends
[Section titled “Extends”](#extends)
* [`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/)<`number`>
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L55)
Number of elements across all sets. O(1).
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`size`](/reference/knotkit/disjoint-set/interfaces/disjointset/#size)
***
### setCount
[Section titled “setCount”](#setcount)
> `readonly` **setCount**: `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L57)
Number of disjoint sets. O(1).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`setCount`](/reference/knotkit/disjoint-set/interfaces/disjointset/#setcount)
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`element`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L59)
Return `true` when the element belongs to the disjoint set. O(1) average.
#### Parameters
[Section titled “Parameters”](#parameters)
##### element
[Section titled “element”](#element)
`number`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`has`](/reference/knotkit/disjoint-set/interfaces/disjointset/#has)
***
### unite
[Section titled “unite”](#unite)
> `readonly` **unite**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L67)
Merge the sets containing `x` and `y`. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
##### y
[Section titled “y”](#y)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
`true` when two distinct sets were merged, `false` when both elements already belonged to the same set.
#### Throws
[Section titled “Throws”](#throws)
When either element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`unite`](/reference/knotkit/disjoint-set/interfaces/disjointset/#unite)
***
### areConnected
[Section titled “areConnected”](#areconnected)
> `readonly` **areConnected**: (`x`, `y`) => `boolean`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L74)
Return `true` when `x` and `y` belong to the same set. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
##### y
[Section titled “y”](#y-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
#### Throws
[Section titled “Throws”](#throws-1)
When either element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`areConnected`](/reference/knotkit/disjoint-set/interfaces/disjointset/#areconnected)
***
### find
[Section titled “find”](#find)
> `readonly` **find**: (`element`) => `number`
Defined in: [packages/disjoint-set/src/disjoint-set.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L81)
Return the representative of the set containing the element. O(alpha(n)) amortized.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### element
[Section titled “element”](#element-1)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
When the element is absent.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`find`](/reference/knotkit/disjoint-set/interfaces/disjointset/#find)
***
### elements
[Section titled “elements”](#elements)
> `readonly` **elements**: () => `IterableIterator`<`number`>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L88)
Iterate over every element in insertion order. O(1) per step, O(n) total.
The iterator covers the elements present when the call was made, so adding elements while iterating does not extend the walk.
#### Returns
[Section titled “Returns”](#returns-4)
`IterableIterator`<`number`>
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`elements`](/reference/knotkit/disjoint-set/interfaces/disjointset/#elements)
***
### sets
[Section titled “sets”](#sets)
> `readonly` **sets**: () => `Map`<`number`, `number`\[]>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:94](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L94)
Collect every set into a `Map` keyed by representative. Members appear in insertion order. O(n \* alpha(n)) time and O(n) space. The result is a copy and does not track later mutations.
#### Returns
[Section titled “Returns”](#returns-5)
`Map`<`number`, `number`\[]>
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`sets`](/reference/knotkit/disjoint-set/interfaces/disjointset/#sets)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"indexed"`
Defined in: [packages/disjoint-set/src/indexed-disjoint-set.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/indexed-disjoint-set.ts#L9)
Stable identifier for the implementation’s storage layout.
#### Overrides
[Section titled “Overrides”](#overrides)
[`DisjointSet`](/reference/knotkit/disjoint-set/interfaces/disjointset/).[`kind`](/reference/knotkit/disjoint-set/interfaces/disjointset/#kind)
***
### append
[Section titled “append”](#append)
> `readonly` **append**: () => `number`
Defined in: [packages/disjoint-set/src/indexed-disjoint-set.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/indexed-disjoint-set.ts#L11)
Append and return the next dense index. O(1) amortized.
#### Returns
[Section titled “Returns”](#returns-6)
`number`
# DisjointSetErrorCode
> **DisjointSetErrorCode** = [`DisjointSetInvalidInputErrorCode`](/reference/knotkit/disjoint-set/type-aliases/disjointsetinvalidinputerrorcode/) | [`DisjointSetParseErrorCode`](/reference/knotkit/disjoint-set/type-aliases/disjointsetparseerrorcode/)
Defined in: [packages/disjoint-set/src/errors.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L50)
A machine-readable error code emitted by `knotkit/disjoint-set`.
# DisjointSetInvalidInputErrorCode
> **DisjointSetInvalidInputErrorCode** = *typeof* [`DISJOINT_SET_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/disjoint-set/variables/disjoint_set_invalid_input_error_codes/)\[`number`]
Defined in: [packages/disjoint-set/src/errors.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L44)
# DisjointSetKind
> **DisjointSetKind** = *typeof* [`DISJOINT_SET_KINDS`](/reference/knotkit/disjoint-set/variables/disjoint_set_kinds/)\[`number`]
Defined in: [packages/disjoint-set/src/disjoint-set.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L121)
Storage layouts provided by this package.
# DisjointSetParseErrorCode
> **DisjointSetParseErrorCode** = *typeof* [`DISJOINT_SET_PARSE_ERROR_CODES`](/reference/knotkit/disjoint-set/variables/disjoint_set_parse_error_codes/)\[`number`]
Defined in: [packages/disjoint-set/src/errors.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L47)
A machine-readable parse code emitted by `knotkit/disjoint-set`.
# GrowableDisjointSetFactory
> **GrowableDisjointSetFactory** = <`T`>(`elements?`) => [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/disjoint-set.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L142)
Create a [DisjointSet](/reference/knotkit/disjoint-set/interfaces/disjointset/) from an optional iterable of elements, each starting in its own singleton set.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### elements?
[Section titled “elements?”](#elements)
`Iterable`<`T`>
## Returns
[Section titled “Returns”](#returns)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
# GrowableDisjointSetKind
> **GrowableDisjointSetKind** = *typeof* [`GROWABLE_DISJOINT_SET_KINDS`](/reference/knotkit/disjoint-set/variables/growable_disjoint_set_kinds/)\[`number`]
Defined in: [packages/disjoint-set/src/disjoint-set.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L136)
Storage layouts that accept new elements after construction.
# DISJOINT_SET_ERROR_CODES
> `const` **DISJOINT_SET_ERROR_CODES**: readonly [`DisjointSetErrorCode`](/reference/knotkit/disjoint-set/type-aliases/disjointseterrorcode/)\[]
Defined in: [packages/disjoint-set/src/errors.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L53)
Every code emitted by `knotkit/disjoint-set`, in stable category order.
# DISJOINT_SET_INVALID_INPUT_ERROR_CODES
> `const` **DISJOINT_SET_INVALID_INPUT_ERROR_CODES**: readonly \[`"ELEMENT_NOT_FOUND"`, `"ELEMENT_ALREADY_REGISTERED"`, `"SIZE_OUT_OF_RANGE"`, `"MAX_SIZE_EXCEEDED"`, `"MISSING_ELEMENT_CODEC"`, `"INVALID_CODEC_RESULT"`, `"NON_INJECTIVE_CODEC"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/disjoint-set/src/errors.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L7)
The canonical, ordered list of machine-readable error codes emitted by `knotkit/disjoint-set`’s public API.
# DISJOINT_SET_KINDS
> `const` **DISJOINT_SET_KINDS**: readonly \[`"indexed"`, `"object"`, `"struct-of-arrays"`]
Defined in: [packages/disjoint-set/src/disjoint-set.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L118)
Every storage layout this package provides, as a runtime value.
Exported so a caller can enumerate the layouts exhaustively without restating them, and so [DisjointSetKind](/reference/knotkit/disjoint-set/type-aliases/disjointsetkind/) is derived from the list rather than duplicating it. `__GROWABLE_DISJOINT_SET_LAYOUTS` in `layouts.ts` is the matching construction table.
# DISJOINT_SET_PARSE_ERROR_CODES
> `const` **DISJOINT_SET_PARSE_ERROR_CODES**: readonly \[`"INVALID_SHAPE"`, `"UNSUPPORTED_SCHEMA_VERSION"`, `"UNKNOWN_KIND"`, `"MISSING_ELEMENTS"`, `"INVALID_LABELS"`, `"INVALID_INDEXED_ELEMENT"`, `"INVALID_ELEMENT"`, `"ELEMENTS_LABELS_LENGTH_MISMATCH"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`, `"INVALID_PACKAGE_HEADER"`, `"DUPLICATE_ELEMENT"`]
Defined in: [packages/disjoint-set/src/errors.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/errors.ts#L19)
Codes carried specifically by [DisjointSetParseError](/reference/knotkit/disjoint-set/classes/disjointsetparseerror/).
# GROWABLE_DISJOINT_SET_KINDS
> `const` **GROWABLE_DISJOINT_SET_KINDS**: readonly \[`"object"`, `"struct-of-arrays"`]
Defined in: [packages/disjoint-set/src/disjoint-set.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/disjoint-set.ts#L133)
The layouts whose element domain can grow after construction, and which therefore share the [GrowableDisjointSetFactory](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/) construction contract.
`indexed` is excluded because it is built from an element count rather than an iterable of elements: it discriminates on a different axis than the two generic layouts, so folding it into one table would require a factory type that fits neither call site.
# __GROWABLE_DISJOINT_SET_LAYOUTS
> `const` **\_\_GROWABLE_DISJOINT_SET_LAYOUTS**: `Readonly`<`Record`<[`GrowableDisjointSetKind`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetkind/), [`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)>>
Defined in: [packages/disjoint-set/src/layouts.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/layouts.ts#L16)
Every growable layout, keyed by the `kind` a set built from it reports.
Iterate this table instead of naming factories one by one: a property sweep, a benchmark, or a caller comparing layouts covers every entry, and a layout added to `GROWABLE_DISJOINT_SET_KINDS` fails to typecheck until it is enrolled here too.
`indexedDisjointSet` is deliberately absent. It is built from an element count rather than an iterable, so it does not satisfy [GrowableDisjointSetFactory](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/); see `GROWABLE_DISJOINT_SET_KINDS`.
# knotkit/disjoint-set/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeDisjointSetOptions](/reference/knotkit/disjoint-set/wire/interfaces/serializedisjointsetoptions/)
* [DeserializeDisjointSetOptions](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetoptions/)
* [SerializedGrowableDisjointSet](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)
* [SerializedIndexedDisjointSet](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
* [DeserializeDisjointSetJsonOptions](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetjsonoptions/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/)
* [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)
## Variables
[Section titled “Variables”](#variables)
* [DISJOINT_SET_MAX_DECODE_ELEMENTS](/reference/knotkit/disjoint-set/wire/variables/disjoint_set_max_decode_elements/)
## Functions
[Section titled “Functions”](#functions)
* [serializeDisjointSet](/reference/knotkit/disjoint-set/wire/functions/serializedisjointset/)
* [deserializeDisjointSet](/reference/knotkit/disjoint-set/wire/functions/deserializedisjointset/)
* [serializeDisjointSetJson](/reference/knotkit/disjoint-set/wire/functions/serializedisjointsetjson/)
* [deserializeDisjointSetJson](/reference/knotkit/disjoint-set/wire/functions/deserializedisjointsetjson/)
# deserializeDisjointSet
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializeDisjointSet**<`T`>(`value`, `options`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/binary.ts:154](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L154)
Restore a canonical binary partition after validating all geometry, counts, codec results, and duplicate elements into staging arrays.
An indexed artifact restored through a growable factory receives the dense numeric elements `0..size - 1`.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### T
[Section titled “T”](#t)
`T`
### Parameters
[Section titled “Parameters”](#parameters)
#### value
[Section titled “value”](#value)
`unknown`
#### options
[Section titled “options”](#options)
[`DeserializeDisjointSetOptions`](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetoptions/)<`T`> & `object`
### Returns
[Section titled “Returns”](#returns)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws)
For malformed bytes, unsupported versions, invalid codec results, duplicate elements, or decode-budget violations. Distinguish causes with `error.code`.
### Throws
[Section titled “Throws”](#throws-1)
With `MISSING_ELEMENT_CODEC` when a growable artifact is decoded without the codec that produced it.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializeDisjointSet**<`T`>(`value`, `options`): [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/) | [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/binary.ts:161](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L161)
Restore a canonical binary partition after validating all geometry, counts, codec results, and duplicate elements into staging arrays.
An indexed artifact restored through a growable factory receives the dense numeric elements `0..size - 1`.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### T
[Section titled “T”](#t-1)
`T`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### value
[Section titled “value”](#value-1)
`unknown`
#### options
[Section titled “options”](#options-1)
[`DeserializeDisjointSetOptions`](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetoptions/)<`T`> & `object`
### Returns
[Section titled “Returns”](#returns-1)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/) | [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws-2)
For malformed bytes, unsupported versions, invalid codec results, duplicate elements, or decode-budget violations. Distinguish causes with `error.code`.
### Throws
[Section titled “Throws”](#throws-3)
With `MISSING_ELEMENT_CODEC` when a growable artifact is decoded without the codec that produced it.
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializeDisjointSet**(`value`, `options?`): [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/) | [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number`>
Defined in: [packages/disjoint-set/src/serialization/binary.ts:165](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L165)
Restore a canonical binary partition after validating all geometry, counts, codec results, and duplicate elements into staging arrays.
An indexed artifact restored through a growable factory receives the dense numeric elements `0..size - 1`.
### Parameters
[Section titled “Parameters”](#parameters-2)
#### value
[Section titled “value”](#value-2)
`unknown`
#### options?
[Section titled “options?”](#options-2)
[`DeserializeDisjointSetOptions`](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetoptions/)<`number`>
### Returns
[Section titled “Returns”](#returns-2)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/) | [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number`>
### Throws
[Section titled “Throws”](#throws-4)
For malformed bytes, unsupported versions, invalid codec results, duplicate elements, or decode-budget violations. Distinguish causes with `error.code`.
### Throws
[Section titled “Throws”](#throws-5)
With `MISSING_ELEMENT_CODEC` when a growable artifact is decoded without the codec that produced it.
# deserializeDisjointSetJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializeDisjointSetJson**<`T`>(`serialized`, `create`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:234](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L234)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### T
[Section titled “T”](#t)
`T`
### Parameters
[Section titled “Parameters”](#parameters)
#### serialized
[Section titled “serialized”](#serialized)
[`SerializedGrowableDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)<`T`>
The partition to restore, either statically typed or decoded as `unknown`.
#### create
[Section titled “create”](#create)
[`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
### Returns
[Section titled “Returns”](#returns)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-1)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializeDisjointSetJson**<`T`>(`serialized`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:238](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L238)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### T
[Section titled “T”](#t-1)
`T`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### serialized
[Section titled “serialized”](#serialized-1)
[`SerializedGrowableDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)<`T`>
The partition to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-1)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws-2)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-3)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializeDisjointSetJson**(`serialized`, `create`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:239](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L239)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Parameters
[Section titled “Parameters”](#parameters-2)
#### serialized
[Section titled “serialized”](#serialized-2)
[`SerializedIndexedDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
The partition to restore, either statically typed or decoded as `unknown`.
#### create
[Section titled “create”](#create-1)
[`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
### Returns
[Section titled “Returns”](#returns-2)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number`>
### Throws
[Section titled “Throws”](#throws-4)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-5)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-3)
> **deserializeDisjointSetJson**(`serialized`): [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
Defined in: [packages/disjoint-set/src/serialization/json.ts:243](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L243)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Parameters
[Section titled “Parameters”](#parameters-3)
#### serialized
[Section titled “serialized”](#serialized-3)
[`SerializedIndexedDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
The partition to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-3)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
### Throws
[Section titled “Throws”](#throws-6)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-7)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-4)
> **deserializeDisjointSetJson**<`T`>(`serialized`, `create`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number` | `T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:244](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L244)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-2)
#### T
[Section titled “T”](#t-2)
`T`
### Parameters
[Section titled “Parameters”](#parameters-4)
#### serialized
[Section titled “serialized”](#serialized-4)
[`SerializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/)<`T`>
The partition to restore, either statically typed or decoded as `unknown`.
#### create
[Section titled “create”](#create-2)
[`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
### Returns
[Section titled “Returns”](#returns-4)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`number` | `T`>
### Throws
[Section titled “Throws”](#throws-8)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-9)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-5)
> **deserializeDisjointSetJson**<`T`>(`serialized`): [`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:248](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L248)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-3)
#### T
[Section titled “T”](#t-3)
`T`
### Parameters
[Section titled “Parameters”](#parameters-5)
#### serialized
[Section titled “serialized”](#serialized-5)
[`SerializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/)<`T`>
The partition to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-5)
[`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws-10)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-11)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-6)
> **deserializeDisjointSetJson**<`T`>(`serialized`, `options`): [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:249](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L249)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-4)
#### T
[Section titled “T”](#t-4)
`T`
### Parameters
[Section titled “Parameters”](#parameters-6)
#### serialized
[Section titled “serialized”](#serialized-6)
`unknown`
The partition to restore, either statically typed or decoded as `unknown`.
#### options
[Section titled “options”](#options)
[`DeserializeDisjointSetJsonOptions`](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetjsonoptions/)<`T`> & `object`
### Returns
[Section titled “Returns”](#returns-6)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws-12)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-13)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-7)
> **deserializeDisjointSetJson**<`T`>(`serialized`, `options`): [`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:253](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L253)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-5)
#### T
[Section titled “T”](#t-5)
`T`
### Parameters
[Section titled “Parameters”](#parameters-7)
#### serialized
[Section titled “serialized”](#serialized-7)
`unknown`
The partition to restore, either statically typed or decoded as `unknown`.
#### options
[Section titled “options”](#options-1)
[`DeserializeDisjointSetJsonOptions`](/reference/knotkit/disjoint-set/wire/interfaces/deserializedisjointsetjsonoptions/)<`T`>
### Returns
[Section titled “Returns”](#returns-7)
[`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`T`>
### Throws
[Section titled “Throws”](#throws-14)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-15)
When an element occurs twice.
## Call Signature
[Section titled “Call Signature”](#call-signature-8)
> **deserializeDisjointSetJson**(`serialized`): [`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`unknown`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:257](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L257)
Rebuild a disjoint set from a [SerializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/serializeddisjointset/), restoring its recorded implementation unless a factory override is supplied. O(n \* alpha(n)) time.
Elements are added in serialized order, then every element is merged with the first element carrying its label. A round trip through `serializeDisjointSetJson` and `deserializeDisjointSetJson` preserves `size`, `setCount`, element order, and connectivity. It does not preserve which member is the representative.
Untyped input produces a [DeserializedDisjointSet](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/) of `unknown` because the runtime `kind` may select either a generic layout or the numeric indexed layout. Pass an element type guard to validate generic decoded values.
### Parameters
[Section titled “Parameters”](#parameters-8)
#### serialized
[Section titled “serialized”](#serialized-8)
`unknown`
The partition to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-8)
[`DeserializedDisjointSet`](/reference/knotkit/disjoint-set/wire/type-aliases/deserializeddisjointset/)<`unknown`>
### Throws
[Section titled “Throws”](#throws-16)
When the serialized shape or an element is invalid, or the two arrays have different lengths. Distinguish causes with `error.code`, one of DisjointSetErrorCode.
### Throws
[Section titled “Throws”](#throws-17)
When an element occurs twice.
# serializeDisjointSet
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **serializeDisjointSet**(`set`, `options?`): `Uint8Array`
Defined in: [packages/disjoint-set/src/serialization/binary.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L92)
Serialize a partition into canonical binary bytes. Growable layouts require an injective codec; indexed layouts synthesize their dense elements.
### Parameters
[Section titled “Parameters”](#parameters)
#### set
[Section titled “set”](#set)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
#### options?
[Section titled “options?”](#options)
[`SerializeDisjointSetOptions`](/reference/knotkit/disjoint-set/wire/interfaces/serializedisjointsetoptions/)
### Returns
[Section titled “Returns”](#returns)
`Uint8Array`
### Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the input cannot be represented safely.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **serializeDisjointSet**<`T`>(`set`, `codec`, `options?`): `Uint8Array`
Defined in: [packages/disjoint-set/src/serialization/binary.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L93)
Serialize a partition into canonical binary bytes. Growable layouts require an injective codec; indexed layouts synthesize their dense elements.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### T
[Section titled “T”](#t)
`T`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### set
[Section titled “set”](#set-1)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
#### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`T`>
#### options?
[Section titled “options?”](#options-1)
[`SerializeDisjointSetOptions`](/reference/knotkit/disjoint-set/wire/interfaces/serializedisjointsetoptions/)
### Returns
[Section titled “Returns”](#returns-1)
`Uint8Array`
### Throws
[Section titled “Throws”](#throws-1)
With `MISSING_ELEMENT_CODEC`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the input cannot be represented safely.
# serializeDisjointSetJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **serializeDisjointSetJson**(`set`): [`SerializedIndexedDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
Defined in: [packages/disjoint-set/src/serialization/json.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L69)
Capture the implementation kind and partition of a disjoint set. O(n \* alpha(n)) time and O(n) space.
Only the partition is captured. Labels are assigned from 0 upwards in order of first appearance, so structures with the same partition and element order serialize identically.
### Parameters
[Section titled “Parameters”](#parameters)
#### set
[Section titled “set”](#set)
[`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
### Returns
[Section titled “Returns”](#returns)
[`SerializedIndexedDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **serializeDisjointSetJson**<`T`>(`set`): [`SerializedGrowableDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/json.ts:70](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L70)
Capture the implementation kind and partition of a disjoint set. O(n \* alpha(n)) time and O(n) space.
Only the partition is captured. Labels are assigned from 0 upwards in order of first appearance, so structures with the same partition and element order serialize identically.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### T
[Section titled “T”](#t)
`T`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### set
[Section titled “set”](#set-1)
[`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`>
### Returns
[Section titled “Returns”](#returns-1)
[`SerializedGrowableDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)<`T`>
# DeserializeDisjointSetJsonOptions
Defined in: [packages/disjoint-set/src/serialization/json.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L54)
Runtime decoding options for data whose element type is not yet known.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### isElement
[Section titled “isElement”](#iselement)
> `readonly` **isElement**: (`value`) => `value is T`
Defined in: [packages/disjoint-set/src/serialization/json.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L56)
Prove the type of every decoded element.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is T`
***
### create?
[Section titled “create?”](#create)
> `readonly` `optional` **create?**: [`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
Defined in: [packages/disjoint-set/src/serialization/json.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L58)
Optional implementation override.
# DeserializeDisjointSetOptions
Defined in: [packages/disjoint-set/src/serialization/binary.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L47)
Runtime inputs needed to decode a generic binary element run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### codec?
[Section titled “codec?”](#codec)
> `readonly` `optional` **codec?**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`T`>
Defined in: [packages/disjoint-set/src/serialization/binary.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L49)
Codec matching the one used to serialize a growable layout.
***
### isElement?
[Section titled “isElement?”](#iselement)
> `readonly` `optional` **isElement?**: (`value`) => `value is T`
Defined in: [packages/disjoint-set/src/serialization/binary.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L51)
Optional validation applied to every decoded codec result.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is T`
***
### create?
[Section titled “create?”](#create)
> `readonly` `optional` **create?**: [`GrowableDisjointSetFactory`](/reference/knotkit/disjoint-set/type-aliases/growabledisjointsetfactory/)
Defined in: [packages/disjoint-set/src/serialization/binary.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L53)
Restore into a growable layout other than the artifact’s recorded kind.
# SerializedGrowableDisjointSet
Defined in: [packages/disjoint-set/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L28)
A plain, inert description of a partition. It holds no behavior and no reference to the structure it came from, so it can be stored, compared, structurally cloned, or sent through `postMessage`. It survives `JSON.stringify` when the elements themselves do.
`kind` identifies the storage layout to restore. The two arrays are parallel and always have the same length. `labels[i]` is the group of `elements[i]`. Labels are opaque. Two elements share a set when their labels are equal, and nothing else about the value is meaningful. `serializeDisjointSetJson` emits dense labels counting from 0, and `deserializeDisjointSetJson` accepts any numbers and groups them by equality.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/disjoint-set/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L30)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"object"` | `"struct-of-arrays"`
Defined in: [packages/disjoint-set/src/serialization/json.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L32)
The storage layout to restore when no factory override is supplied.
***
### elements
[Section titled “elements”](#elements)
> `readonly` **elements**: readonly `T`\[]
Defined in: [packages/disjoint-set/src/serialization/json.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L34)
Every element, in the order it was added.
***
### labels
[Section titled “labels”](#labels)
> `readonly` **labels**: readonly `number`\[]
Defined in: [packages/disjoint-set/src/serialization/json.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L36)
The group label of the element at the same position.
# SerializedIndexedDisjointSet
Defined in: [packages/disjoint-set/src/serialization/json.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L40)
A serialized dense integer disjoint set.
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/disjoint-set/src/serialization/json.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L41)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"indexed"`
Defined in: [packages/disjoint-set/src/serialization/json.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L42)
***
### elements
[Section titled “elements”](#elements)
> `readonly` **elements**: readonly `number`\[]
Defined in: [packages/disjoint-set/src/serialization/json.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L43)
***
### labels
[Section titled “labels”](#labels)
> `readonly` **labels**: readonly `number`\[]
Defined in: [packages/disjoint-set/src/serialization/json.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L44)
# SerializeDisjointSetOptions
Defined in: [packages/disjoint-set/src/serialization/binary.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L41)
Options shared by indexed and generic binary serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/disjoint-set/src/serialization/binary.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L43)
Include a CRC-32 integrity section for accidental corruption detection.
# DeserializedDisjointSet
> **DeserializedDisjointSet**<`T`> = [`GrowableDisjointSet`](/reference/knotkit/disjoint-set/interfaces/growabledisjointset/)<`T`> | [`IndexedDisjointSet`](/reference/knotkit/disjoint-set/interfaces/indexeddisjointset/)
Defined in: [packages/disjoint-set/src/serialization/json.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L51)
The result of decoding a payload whose implementation kind is known only at runtime.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
# SerializedDisjointSet
> **SerializedDisjointSet**<`T`> = [`SerializedGrowableDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedgrowabledisjointset/)<`T`> | [`SerializedIndexedDisjointSet`](/reference/knotkit/disjoint-set/wire/interfaces/serializedindexeddisjointset/)
Defined in: [packages/disjoint-set/src/serialization/json.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/json.ts#L48)
Any serialized disjoint-set layout. Indexed payloads always contain numbers.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
# DISJOINT_SET_MAX_DECODE_ELEMENTS
> `const` **DISJOINT_SET_MAX_DECODE_ELEMENTS**: `1000000` = `1_000_000`
Defined in: [packages/disjoint-set/src/serialization/binary.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/disjoint-set/src/serialization/binary.ts#L38)
Maximum element count a binary decoder stages before constructing a set.
# knotkit/distance
## Classes
[Section titled “Classes”](#classes)
* [DistanceInvalidInputError](/reference/knotkit/distance/classes/distanceinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [JaccardOverlap](/reference/knotkit/distance/interfaces/jaccardoverlap/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [DistanceKind](/reference/knotkit/distance/type-aliases/distancekind/)
* [DistanceInputDomain](/reference/knotkit/distance/type-aliases/distanceinputdomain/)
* [DistanceRule](/reference/knotkit/distance/type-aliases/distancerule/)
* [DistanceInvalidInputErrorCode](/reference/knotkit/distance/type-aliases/distanceinvalidinputerrorcode/)
* [DistanceErrorCode](/reference/knotkit/distance/type-aliases/distanceerrorcode/)
* [NumericVector](/reference/knotkit/distance/type-aliases/numericvector/)
## Variables
[Section titled “Variables”](#variables)
* [DISTANCE_KINDS](/reference/knotkit/distance/variables/distance_kinds/)
* [DISTANCE_RULES](/reference/knotkit/distance/variables/distance_rules/)
* [DISTANCE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/distance/variables/distance_invalid_input_error_codes/)
* [DISTANCE_ERROR_CODES](/reference/knotkit/distance/variables/distance_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [cosineSimilarity](/reference/knotkit/distance/functions/cosinesimilarity/)
* [cosineDistance](/reference/knotkit/distance/functions/cosinedistance/)
* [jaccardOverlap](/reference/knotkit/distance/functions/jaccardoverlap/)
* [jaccardSimilarity](/reference/knotkit/distance/functions/jaccardsimilarity/)
* [jaccardDistance](/reference/knotkit/distance/functions/jaccarddistance/)
* [kullbackLeiblerDivergence](/reference/knotkit/distance/functions/kullbackleiblerdivergence/)
* [totalVariationDistance](/reference/knotkit/distance/functions/totalvariationdistance/)
* [manhattanDistance](/reference/knotkit/distance/functions/manhattandistance/)
* [uncheckedSquaredEuclideanDistance](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance/)
* [uncheckedEuclideanDistance2D](/reference/knotkit/distance/functions/uncheckedeuclideandistance2d/)
* [uncheckedSquaredEuclideanDistance2D](/reference/knotkit/distance/functions/uncheckedsquaredeuclideandistance2d/)
* [euclideanDistance](/reference/knotkit/distance/functions/euclideandistance/)
* [squaredEuclideanDistance](/reference/knotkit/distance/functions/squaredeuclideandistance/)
* [meanSquaredError](/reference/knotkit/distance/functions/meansquarederror/)
# DistanceInvalidInputError
Defined in: [packages/distance/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L14)
Thrown when a caller passes an argument or object that violates a public contract: an out-of-range value, a malformed id, or an object not produced by the package’s own factories.
Abstract so every concrete instance belongs to the throwing package’s own subclass, which fixes `Code` to that package’s error-code union and gives `.name` a package-specific value.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`DistanceInvalidInputErrorCode`](/reference/knotkit/distance/type-aliases/distanceinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new DistanceInvalidInputError**(`code`, `message`): `DistanceInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_DIMENSION"` | `"NON_FINITE_COORDINATE"` | `"ZERO_VECTOR"` | `"INVALID_PROBABILITIES"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`DistanceInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/distance"`
Defined in: [packages/distance/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L15)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_DIMENSION"` | `"NON_FINITE_COORDINATE"` | `"ZERO_VECTOR"` | `"INVALID_PROBABILITIES"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# cosineDistance
> **cosineDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/cosine.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/cosine.ts#L48)
One minus cosine similarity, in \[0, 2]. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `NON_FINITE_COORDINATE`, or `ZERO_VECTOR`.
# cosineSimilarity
> **cosineSimilarity**(`first`, `second`): `number`
Defined in: [packages/distance/src/cosine.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/cosine.ts#L38)
The cosine of the angle between nonzero vectors, in \[-1, 1]. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `NON_FINITE_COORDINATE`, or `ZERO_VECTOR`.
# euclideanDistance
> **euclideanDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/vector-distance.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L72)
The straight-line length between two vectors. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `NON_FINITE_COORDINATE`.
# jaccardDistance
> **jaccardDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/jaccard.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L44)
Exact fraction of the union that occurs in only one set. Two empty sets have distance zero. Uses O(min(a.size, b.size)) membership checks and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ReadonlySet`<`unknown`>
### second
[Section titled “second”](#second)
`ReadonlySet`<`unknown`>
## Returns
[Section titled “Returns”](#returns)
`number`
# jaccardOverlap
> **jaccardOverlap**(`first`, `second`): [`JaccardOverlap`](/reference/knotkit/distance/interfaces/jaccardoverlap/)
Defined in: [packages/distance/src/jaccard.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L26)
Count the intersection and union and compute their ratio. Two empty sets have similarity one. Uses O(min(a.size, b.size)) membership checks and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ReadonlySet`<`unknown`>
### second
[Section titled “second”](#second)
`ReadonlySet`<`unknown`>
## Returns
[Section titled “Returns”](#returns)
[`JaccardOverlap`](/reference/knotkit/distance/interfaces/jaccardoverlap/)
# jaccardSimilarity
> **jaccardSimilarity**(`first`, `second`): `number`
Defined in: [packages/distance/src/jaccard.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L36)
Exact intersection size divided by union size. Two empty sets have similarity one. Uses O(min(a.size, b.size)) membership checks and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ReadonlySet`<`unknown`>
### second
[Section titled “second”](#second)
`ReadonlySet`<`unknown`>
## Returns
[Section titled “Returns”](#returns)
`number`
# kullbackLeiblerDivergence
> **kullbackLeiblerDivergence**(`first`, `second`): `number`
Defined in: [packages/distance/src/kullback-leibler.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/kullback-leibler.ts#L34)
Directional relative entropy D(first || second) in nats. The vectors describe the same ordered outcomes. Entries must be probabilities and each total must be within the distribution module’s probability-table tolerance of one. Accepted vectors are normalized by their totals. A positive first mass paired with zero second mass returns Infinity. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `INVALID_PROBABILITIES`.
# manhattanDistance
> **manhattanDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/vector-distance.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L7)
Sum the absolute differences between corresponding coordinates. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `NON_FINITE_COORDINATE`.
# meanSquaredError
> **meanSquaredError**(`first`, `second`): `number`
Defined in: [packages/distance/src/vector-distance.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L99)
Average the squared coordinate differences. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `NON_FINITE_COORDINATE`.
# squaredEuclideanDistance
> **squaredEuclideanDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/vector-distance.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L88)
Sum the squared coordinate differences. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `NON_FINITE_COORDINATE`.
# totalVariationDistance
> **totalVariationDistance**(`first`, `second`): `number`
Defined in: [packages/distance/src/total-variation.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/total-variation.ts#L10)
Largest absolute difference in event probability for two probability vectors on the same ordered outcomes. Accepted vectors are normalized by their totals. Returns a distance in \[0, 1] in O(n) time and O(1) extra space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION` or `INVALID_PROBABILITIES`.
# uncheckedEuclideanDistance2D
> **uncheckedEuclideanDistance2D**(`firstX`, `firstY`, `secondX`, `secondY`): `number`
Defined in: [packages/distance/src/vector-distance.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L44)
Straight-line distance between two planar points. The caller supplies finite coordinates. Takes O(1) time and space.
## Parameters
[Section titled “Parameters”](#parameters)
### firstX
[Section titled “firstX”](#firstx)
`number`
### firstY
[Section titled “firstY”](#firsty)
`number`
### secondX
[Section titled “secondX”](#secondx)
`number`
### secondY
[Section titled “secondY”](#secondy)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
# uncheckedSquaredEuclideanDistance
> **uncheckedSquaredEuclideanDistance**(`first`, `second`, `secondOffset?`): `number`
Defined in: [packages/distance/src/vector-distance.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L24)
Sum squared differences in coordinate order for inputs whose contract was checked by the caller. The second vector may hold packed rows. Its window starts at `secondOffset` and has the length of the first vector. The caller supplies finite coordinates and a valid offset and window. Ordinary binary64 sums can overflow or lose subnormal terms. Takes O(n) time and O(1) space.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### second
[Section titled “second”](#second)
[`NumericVector`](/reference/knotkit/distance/type-aliases/numericvector/)
### secondOffset?
[Section titled “secondOffset?”](#secondoffset)
`number` = `0`
## Returns
[Section titled “Returns”](#returns)
`number`
# uncheckedSquaredEuclideanDistance2D
> **uncheckedSquaredEuclideanDistance2D**(`firstX`, `firstY`, `secondX`, `secondY`): `number`
Defined in: [packages/distance/src/vector-distance.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector-distance.ts#L52)
Sum squared differences between two planar points. The caller supplies finite coordinates. Ordinary binary64 sums can overflow or lose subnormal terms. Takes O(1) time and space.
## Parameters
[Section titled “Parameters”](#parameters)
### firstX
[Section titled “firstX”](#firstx)
`number`
### firstY
[Section titled “firstY”](#firsty)
`number`
### secondX
[Section titled “secondX”](#secondx)
`number`
### secondY
[Section titled “secondY”](#secondy)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
# JaccardOverlap
Defined in: [packages/distance/src/jaccard.ts:2](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L2)
Exact set cardinalities and the Jaccard similarity computed from them.
## Properties
[Section titled “Properties”](#properties)
### intersection
[Section titled “intersection”](#intersection)
> `readonly` **intersection**: `number`
Defined in: [packages/distance/src/jaccard.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L3)
***
### union
[Section titled “union”](#union)
> `readonly` **union**: `number`
Defined in: [packages/distance/src/jaccard.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L4)
***
### similarity
[Section titled “similarity”](#similarity)
> `readonly` **similarity**: `number`
Defined in: [packages/distance/src/jaccard.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/jaccard.ts#L5)
# DistanceErrorCode
> **DistanceErrorCode** = [`DistanceInvalidInputErrorCode`](/reference/knotkit/distance/type-aliases/distanceinvalidinputerrorcode/)
Defined in: [packages/distance/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L11)
# DistanceInputDomain
> **DistanceInputDomain** = `"numeric-vector"` | `"probability-vector"` | `"set"`
Defined in: [packages/distance/src/distance-rules.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/distance-rules.ts#L28)
# DistanceInvalidInputErrorCode
> **DistanceInvalidInputErrorCode** = *typeof* [`DISTANCE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/distance/variables/distance_invalid_input_error_codes/)\[`number`]
Defined in: [packages/distance/src/errors.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L10)
# DistanceKind
> **DistanceKind** = *typeof* [`DISTANCE_KINDS`](/reference/knotkit/distance/variables/distance_kinds/)\[`number`]
Defined in: [packages/distance/src/distance-rules.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/distance-rules.ts#L23)
# DistanceRule
> **DistanceRule** = `DistanceRules`\[[`DistanceKind`](/reference/knotkit/distance/type-aliases/distancekind/)]
Defined in: [packages/distance/src/distance-rules.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/distance-rules.ts#L92)
# NumericVector
> **NumericVector** = `ArrayLike`<`number`>
Defined in: [packages/distance/src/vector.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/vector.ts#L4)
A dense numeric array or typed array.
# DISTANCE_ERROR_CODES
> `const` **DISTANCE_ERROR_CODES**: readonly [`DistanceErrorCode`](/reference/knotkit/distance/type-aliases/distanceerrorcode/)\[]
Defined in: [packages/distance/src/errors.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L12)
# DISTANCE_INVALID_INPUT_ERROR_CODES
> `const` **DISTANCE_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_DIMENSION"`, `"NON_FINITE_COORDINATE"`, `"ZERO_VECTOR"`, `"INVALID_PROBABILITIES"`]
Defined in: [packages/distance/src/errors.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/errors.ts#L3)
# DISTANCE_KINDS
> `const` **DISTANCE_KINDS**: *typeof* `distanceKinds`
Defined in: [packages/distance/src/distance-rules.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/distance-rules.ts#L21)
# DISTANCE_RULES
> `const` **DISTANCE_RULES**: `DistanceRules`
Defined in: [packages/distance/src/distance-rules.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distance/src/distance-rules.ts#L55)
Comparisons and their mathematical guarantees on the declared input domain.
# knotkit/distribution
## Classes
[Section titled “Classes”](#classes)
* [DistributionInvalidInputError](/reference/knotkit/distribution/classes/distributioninvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [BetaDistributionParameters](/reference/knotkit/distribution/interfaces/betadistributionparameters/)
* [BetaDistribution](/reference/knotkit/distribution/interfaces/betadistribution/)
* [BinomialDistributionParameters](/reference/knotkit/distribution/interfaces/binomialdistributionparameters/)
* [BinomialDistribution](/reference/knotkit/distribution/interfaces/binomialdistribution/)
* [ChiSquaredDistributionParameters](/reference/knotkit/distribution/interfaces/chisquareddistributionparameters/)
* [ChiSquaredDistribution](/reference/knotkit/distribution/interfaces/chisquareddistribution/)
* [CustomContinuousDistributionParameters](/reference/knotkit/distribution/interfaces/customcontinuousdistributionparameters/)
* [CustomContinuousDistribution](/reference/knotkit/distribution/interfaces/customcontinuousdistribution/)
* [CustomDiscreteDistributionParameters](/reference/knotkit/distribution/interfaces/customdiscretedistributionparameters/)
* [CustomDiscreteDistribution](/reference/knotkit/distribution/interfaces/customdiscretedistribution/)
* [DistributionSupport](/reference/knotkit/distribution/interfaces/distributionsupport/)
* [CumulativeDistribution](/reference/knotkit/distribution/interfaces/cumulativedistribution/)
* [DiscreteDistribution](/reference/knotkit/distribution/interfaces/discretedistribution/)
* [ContinuousDistribution](/reference/knotkit/distribution/interfaces/continuousdistribution/)
* [DistributionMoments](/reference/knotkit/distribution/interfaces/distributionmoments/)
* [ExponentialDistributionParameters](/reference/knotkit/distribution/interfaces/exponentialdistributionparameters/)
* [ExponentialDistribution](/reference/knotkit/distribution/interfaces/exponentialdistribution/)
* [FDistributionParameters](/reference/knotkit/distribution/interfaces/fdistributionparameters/)
* [FDistribution](/reference/knotkit/distribution/interfaces/fdistribution/)
* [GammaDistributionParameters](/reference/knotkit/distribution/interfaces/gammadistributionparameters/)
* [GammaDistribution](/reference/knotkit/distribution/interfaces/gammadistribution/)
* [GeometricDistributionParameters](/reference/knotkit/distribution/interfaces/geometricdistributionparameters/)
* [GeometricDistribution](/reference/knotkit/distribution/interfaces/geometricdistribution/)
* [HypergeometricDistributionParameters](/reference/knotkit/distribution/interfaces/hypergeometricdistributionparameters/)
* [HypergeometricDistribution](/reference/knotkit/distribution/interfaces/hypergeometricdistribution/)
* [DiscreteDistributionParametersByKind](/reference/knotkit/distribution/interfaces/discretedistributionparametersbykind/)
* [ContinuousDistributionParametersByKind](/reference/knotkit/distribution/interfaces/continuousdistributionparametersbykind/)
* [CustomDistributionParametersByKind](/reference/knotkit/distribution/interfaces/customdistributionparametersbykind/)
* [LogNormalDistributionParameters](/reference/knotkit/distribution/interfaces/lognormaldistributionparameters/)
* [LogNormalDistribution](/reference/knotkit/distribution/interfaces/lognormaldistribution/)
* [NormalDistributionParameters](/reference/knotkit/distribution/interfaces/normaldistributionparameters/)
* [NormalDistribution](/reference/knotkit/distribution/interfaces/normaldistribution/)
* [PoissonDistributionParameters](/reference/knotkit/distribution/interfaces/poissondistributionparameters/)
* [PoissonDistribution](/reference/knotkit/distribution/interfaces/poissondistribution/)
* [ProbabilityTableDistributionParameters](/reference/knotkit/distribution/interfaces/probabilitytabledistributionparameters/)
* [ProbabilityTableDistribution](/reference/knotkit/distribution/interfaces/probabilitytabledistribution/)
* [SampleMomentOptions](/reference/knotkit/distribution/interfaces/samplemomentoptions/)
* [HistogramBinsOptions](/reference/knotkit/distribution/interfaces/histogrambinsoptions/)
* [HistogramEdgesOptions](/reference/knotkit/distribution/interfaces/histogramedgesoptions/)
* [Histogram](/reference/knotkit/distribution/interfaces/histogram/)
* [StudentTDistributionParameters](/reference/knotkit/distribution/interfaces/studenttdistributionparameters/)
* [StudentTDistribution](/reference/knotkit/distribution/interfaces/studenttdistribution/)
* [UniformDistributionParameters](/reference/knotkit/distribution/interfaces/uniformdistributionparameters/)
* [UniformDistribution](/reference/knotkit/distribution/interfaces/uniformdistribution/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [DistributionInvalidInputErrorCode](/reference/knotkit/distribution/type-aliases/distributioninvalidinputerrorcode/)
* [DistributionErrorCode](/reference/knotkit/distribution/type-aliases/distributionerrorcode/)
* [NumericSample](/reference/knotkit/distribution/type-aliases/numericsample/)
* [DiscreteDistributionKind](/reference/knotkit/distribution/type-aliases/discretedistributionkind/)
* [ContinuousDistributionKind](/reference/knotkit/distribution/type-aliases/continuousdistributionkind/)
* [CustomDistributionKind](/reference/knotkit/distribution/type-aliases/customdistributionkind/)
* [Probability](/reference/knotkit/distribution/type-aliases/probability/)
* [HistogramOptions](/reference/knotkit/distribution/type-aliases/histogramoptions/)
## Variables
[Section titled “Variables”](#variables)
* [BETA_MIN_SHAPE](/reference/knotkit/distribution/variables/beta_min_shape/)
* [BETA_MAX_SHAPE](/reference/knotkit/distribution/variables/beta_max_shape/)
* [BINOMIAL_MAX_TRIALS](/reference/knotkit/distribution/variables/binomial_max_trials/)
* [CHI_SQUARED_MIN_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/chi_squared_min_degrees_of_freedom/)
* [CHI_SQUARED_MAX_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/chi_squared_max_degrees_of_freedom/)
* [DISTRIBUTION_INVALID_INPUT_ERROR_CODES](/reference/knotkit/distribution/variables/distribution_invalid_input_error_codes/)
* [DISTRIBUTION_ERROR_CODES](/reference/knotkit/distribution/variables/distribution_error_codes/)
* [EXPONENTIAL_MIN_RATE](/reference/knotkit/distribution/variables/exponential_min_rate/)
* [EXPONENTIAL_MAX_RATE](/reference/knotkit/distribution/variables/exponential_max_rate/)
* [F_MIN_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/f_min_degrees_of_freedom/)
* [F_MAX_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/f_max_degrees_of_freedom/)
* [GAMMA_MIN_SHAPE](/reference/knotkit/distribution/variables/gamma_min_shape/)
* [GAMMA_MAX_SHAPE](/reference/knotkit/distribution/variables/gamma_max_shape/)
* [GAMMA_MIN_RATE](/reference/knotkit/distribution/variables/gamma_min_rate/)
* [GAMMA_MAX_RATE](/reference/knotkit/distribution/variables/gamma_max_rate/)
* [GEOMETRIC_MIN_SUCCESS_PROBABILITY](/reference/knotkit/distribution/variables/geometric_min_success_probability/)
* [HYPERGEOMETRIC_MAX_POPULATION_SIZE](/reference/knotkit/distribution/variables/hypergeometric_max_population_size/)
* [DISTRIBUTION_MAX_MOMENT_ORDER](/reference/knotkit/distribution/variables/distribution_max_moment_order/)
* [DISCRETE_DISTRIBUTION_KINDS](/reference/knotkit/distribution/variables/discrete_distribution_kinds/)
* [\_\_DISCRETE_DISTRIBUTION_LAYOUTS](/reference/knotkit/distribution/variables/discrete_distribution_layouts/)
* [CONTINUOUS_DISTRIBUTION_KINDS](/reference/knotkit/distribution/variables/continuous_distribution_kinds/)
* [\_\_CONTINUOUS_DISTRIBUTION_LAYOUTS](/reference/knotkit/distribution/variables/continuous_distribution_layouts/)
* [CUSTOM_DISTRIBUTION_KINDS](/reference/knotkit/distribution/variables/custom_distribution_kinds/)
* [\_\_CUSTOM_DISTRIBUTION_LAYOUTS](/reference/knotkit/distribution/variables/custom_distribution_layouts/)
* [LOG_NORMAL_MAX_ABSOLUTE_LOG_MEAN](/reference/knotkit/distribution/variables/log_normal_max_absolute_log_mean/)
* [LOG_NORMAL_MAX_LOG_STANDARD_DEVIATION](/reference/knotkit/distribution/variables/log_normal_max_log_standard_deviation/)
* [NORMAL_MAX_ABSOLUTE_MEAN](/reference/knotkit/distribution/variables/normal_max_absolute_mean/)
* [NORMAL_MAX_STANDARD_DEVIATION](/reference/knotkit/distribution/variables/normal_max_standard_deviation/)
* [POISSON_MAX_MEAN](/reference/knotkit/distribution/variables/poisson_max_mean/)
* [PROBABILITY_TABLE_SUM_TOLERANCE](/reference/knotkit/distribution/variables/probability_table_sum_tolerance/)
* [Probability](/reference/knotkit/distribution/variables/probability/)
* [STUDENT_T_MIN_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/student_t_min_degrees_of_freedom/)
* [STUDENT_T_MAX_DEGREES_OF_FREEDOM](/reference/knotkit/distribution/variables/student_t_max_degrees_of_freedom/)
## Functions
[Section titled “Functions”](#functions)
* [betaDistribution](/reference/knotkit/distribution/functions/betadistribution/)
* [binomialDistribution](/reference/knotkit/distribution/functions/binomialdistribution/)
* [chiSquaredDistribution](/reference/knotkit/distribution/functions/chisquareddistribution/)
* [customContinuousDistribution](/reference/knotkit/distribution/functions/customcontinuousdistribution/)
* [customDiscreteDistribution](/reference/knotkit/distribution/functions/customdiscretedistribution/)
* [exponentialDistribution](/reference/knotkit/distribution/functions/exponentialdistribution/)
* [fDistribution](/reference/knotkit/distribution/functions/fdistribution/)
* [gammaDistribution](/reference/knotkit/distribution/functions/gammadistribution/)
* [geometricDistribution](/reference/knotkit/distribution/functions/geometricdistribution/)
* [hypergeometricDistribution](/reference/knotkit/distribution/functions/hypergeometricdistribution/)
* [logNormalDistribution](/reference/knotkit/distribution/functions/lognormaldistribution/)
* [normalDistribution](/reference/knotkit/distribution/functions/normaldistribution/)
* [poissonDistribution](/reference/knotkit/distribution/functions/poissondistribution/)
* [probabilityTableDistribution](/reference/knotkit/distribution/functions/probabilitytabledistribution/)
* [isProbabilityVector](/reference/knotkit/distribution/functions/isprobabilityvector/)
* [isProbability](/reference/knotkit/distribution/functions/isprobability/)
* [sampleMean](/reference/knotkit/distribution/functions/samplemean/)
* [sampleVariance](/reference/knotkit/distribution/functions/samplevariance/)
* [median](/reference/knotkit/distribution/functions/median/)
* [sampleQuantile](/reference/knotkit/distribution/functions/samplequantile/)
* [histogram](/reference/knotkit/distribution/functions/histogram/)
* [covariance](/reference/knotkit/distribution/functions/covariance/)
* [pearsonCorrelation](/reference/knotkit/distribution/functions/pearsoncorrelation/)
* [studentTDistribution](/reference/knotkit/distribution/functions/studenttdistribution/)
* [uniformDistribution](/reference/knotkit/distribution/functions/uniformdistribution/)
# DistributionInvalidInputError
Defined in: [packages/distribution/src/errors.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L27)
Thrown when an input cannot describe or evaluate a distribution.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`DistributionInvalidInputErrorCode`](/reference/knotkit/distribution/type-aliases/distributioninvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new DistributionInvalidInputError**(`code`, `message`): `DistributionInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_ARGUMENT"` | `"INVALID_PARAMETER"` | `"INVALID_PROBABILITY"` | `"INVALID_MOMENT_ORDER"` | `"INVALID_TABLE"` | `"INVALID_CALLBACK_VALUE"` | `"QUANTILE_NOT_BRACKETED"` | `"INVALID_SAMPLE"` | `"ZERO_VARIANCE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`DistributionInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/distribution"`
Defined in: [packages/distribution/src/errors.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L28)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_ARGUMENT"` | `"INVALID_PARAMETER"` | `"INVALID_PROBABILITY"` | `"INVALID_MOMENT_ORDER"` | `"INVALID_TABLE"` | `"INVALID_CALLBACK_VALUE"` | `"QUANTILE_NOT_BRACKETED"` | `"INVALID_SAMPLE"` | `"ZERO_VARIANCE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# betaDistribution
> **betaDistribution**(`parameters`): [`BetaDistribution`](/reference/knotkit/distribution/interfaces/betadistribution/)
Defined in: [packages/distribution/src/beta-distribution.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L33)
Create a beta distribution with the given shapes. Each draw normalizes two gamma draws and consumes a variable number of 32-bit words. Small-shape pairs use log-space normalization. Rounding at an endpoint keeps the result interior.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`BetaDistributionParameters`](/reference/knotkit/distribution/interfaces/betadistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`BetaDistribution`](/reference/knotkit/distribution/interfaces/betadistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported alpha or beta shape.
# binomialDistribution
> **binomialDistribution**(`__namedParameters`): [`BinomialDistribution`](/reference/knotkit/distribution/interfaces/binomialdistribution/)
Defined in: [packages/distribution/src/binomial-distribution.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L33)
Construct a binomial count distribution. Zero trials or a success probability of zero or one give a point mass.
Draws consume two 32-bit words for a point mass or when the expected smaller outcome count is below 10, and a variable number otherwise.
## Parameters
[Section titled “Parameters”](#parameters)
### \_\_namedParameters
[Section titled “\_\_namedParameters”](#__namedparameters)
[`BinomialDistributionParameters`](/reference/knotkit/distribution/interfaces/binomialdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`BinomialDistribution`](/reference/knotkit/distribution/interfaces/binomialdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for unsupported trials or success probability.
# chiSquaredDistribution
> **chiSquaredDistribution**(`parameters`): [`ChiSquaredDistribution`](/reference/knotkit/distribution/interfaces/chisquareddistribution/)
Defined in: [packages/distribution/src/chi-squared-distribution.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L26)
Create a chi-squared distribution, equivalent to a gamma with half the degrees of freedom as shape and rate one half. Each rejection draw consumes a variable number of 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`ChiSquaredDistributionParameters`](/reference/knotkit/distribution/interfaces/chisquareddistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`ChiSquaredDistribution`](/reference/knotkit/distribution/interfaces/chisquareddistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for unsupported degrees of freedom.
# covariance
> **covariance**(`first`, `second`, `options?`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:250](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L250)
Covariance by Welford’s one-pass co-moment update. The divisor is `length - degreesOfFreedomCorrection`; the default `1` is the unbiased sample covariance.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### second
[Section titled “second”](#second)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### options?
[Section titled “options?”](#options)
[`SampleMomentOptions`](/reference/knotkit/distribution/interfaces/samplemomentoptions/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_PARAMETER` when the correction is not a nonnegative integer; `INVALID_SAMPLE` when the lengths differ, a value is non-finite, or the length does not exceed the correction.
# customContinuousDistribution
> **customContinuousDistribution**(`parameters`): [`CustomContinuousDistribution`](/reference/knotkit/distribution/interfaces/customcontinuousdistribution/)
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L33)
Build a distribution with a monotone CDF and a nonnegative density. Omitted survival and quantile functions are derived from the CDF. The quantile of a non-monotone CDF is unspecified.
Draws consume two 32-bit words and replay only when the callbacks are deterministic.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`CustomContinuousDistributionParameters`](/reference/knotkit/distribution/interfaces/customcontinuousdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`CustomContinuousDistribution`](/reference/knotkit/distribution/interfaces/customcontinuousdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for a disordered support or invalid callback. Calls to the returned distribution throw `INVALID_CALLBACK_VALUE` when a consumed callback result is outside its range.
# customDiscreteDistribution
> **customDiscreteDistribution**(`parameters`): [`CustomDiscreteDistribution`](/reference/knotkit/distribution/interfaces/customdiscretedistribution/)
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L32)
Build a distribution over integer outcomes. Infinite upper support requires the cumulative callback. Finite tails sum the supplied masses on their own side. Infinite survival uses the complement of the CDF.
Draws consume two 32-bit words and replay only when the callbacks are deterministic.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`CustomDiscreteDistributionParameters`](/reference/knotkit/distribution/interfaces/customdiscretedistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`CustomDiscreteDistribution`](/reference/knotkit/distribution/interfaces/customdiscretedistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for invalid bounds or missing callbacks. Calls to the returned distribution throw `INVALID_CALLBACK_VALUE` when a consumed callback result is outside \[0, 1].
# exponentialDistribution
> **exponentialDistribution**(`parameters`): [`ExponentialDistribution`](/reference/knotkit/distribution/interfaces/exponentialdistribution/)
Defined in: [packages/distribution/src/exponential-distribution.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L24)
Create an exponential distribution with mean equal to the reciprocal of the rate. Each draw uses two 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`ExponentialDistributionParameters`](/reference/knotkit/distribution/interfaces/exponentialdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`ExponentialDistribution`](/reference/knotkit/distribution/interfaces/exponentialdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported rate.
# fDistribution
> **fDistribution**(`parameters`): [`FDistribution`](/reference/knotkit/distribution/interfaces/fdistribution/)
Defined in: [packages/distribution/src/f-distribution.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L31)
Create an F distribution, the ratio of two chi-squared variables each divided by its degrees of freedom. Tails use the regularized incomplete beta function. Each draw consumes a variable number of 32-bit words and rounds to the finite positive doubles.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`FDistributionParameters`](/reference/knotkit/distribution/interfaces/fdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`FDistribution`](/reference/knotkit/distribution/interfaces/fdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for unsupported degrees of freedom.
# gammaDistribution
> **gammaDistribution**(`parameters`): [`GammaDistribution`](/reference/knotkit/distribution/interfaces/gammadistribution/)
Defined in: [packages/distribution/src/gamma-distribution.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L30)
Create a gamma distribution with the given shape and rate. Each rejection draw consumes a variable number of 32-bit words. Shapes below one use a log-space boost. A positive draw beneath binary64’s range rounds to the smallest positive double.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`GammaDistributionParameters`](/reference/knotkit/distribution/interfaces/gammadistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`GammaDistribution`](/reference/knotkit/distribution/interfaces/gammadistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported shape or rate.
# geometricDistribution
> **geometricDistribution**(`__namedParameters`): [`GeometricDistribution`](/reference/knotkit/distribution/interfaces/geometricdistribution/)
Defined in: [packages/distribution/src/geometric-distribution.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/geometric-distribution.ts#L28)
Construct the distribution of failures before the first success. A success probability of one gives a point mass at zero.
Draws consume two 32-bit words for closed-form inversion, including point masses.
## Parameters
[Section titled “Parameters”](#parameters)
### \_\_namedParameters
[Section titled “\_\_namedParameters”](#__namedparameters)
[`GeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/geometricdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`GeometricDistribution`](/reference/knotkit/distribution/interfaces/geometricdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported success probability.
# histogram
> **histogram**(`values`, `options`): [`Histogram`](/reference/knotkit/distribution/interfaces/histogram/)
Defined in: [packages/distribution/src/sample-statistics.ts:210](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L210)
Histogram with NumPy’s `np.histogram` semantics: bin `i` is `[edges[i], edges[i + 1])` and the last bin is closed on both ends. `{ bins }` spans the sample’s range with equal-width bins, widened by 0.5 on each side when the sample is constant. `{ edges }` uses the supplied edges, and values outside them are not counted. The input is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### options
[Section titled “options”](#options)
[`HistogramOptions`](/reference/knotkit/distribution/type-aliases/histogramoptions/)
## Returns
[Section titled “Returns”](#returns)
[`Histogram`](/reference/knotkit/distribution/interfaces/histogram/)
## Throws
[Section titled “Throws”](#throws)
`INVALID_SAMPLE` when `values` is empty or holds a non-finite value; `INVALID_PARAMETER` when `bins` is not a positive integer or `edges` are not at least 2 finite, strictly increasing numbers.
# hypergeometricDistribution
> **hypergeometricDistribution**(`__namedParameters`): [`HypergeometricDistribution`](/reference/knotkit/distribution/interfaces/hypergeometricdistribution/)
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L74)
Construct the count distribution for draws without replacement.
Draws consume two 32-bit words for a point mass or when the sample or its complement has fewer than 10 items. The wider case uses ratio-of- uniforms rejection and a variable number of words.
## Parameters
[Section titled “Parameters”](#parameters)
### \_\_namedParameters
[Section titled “\_\_namedParameters”](#__namedparameters)
[`HypergeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/hypergeometricdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`HypergeometricDistribution`](/reference/knotkit/distribution/interfaces/hypergeometricdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported count.
# isProbability
> **isProbability**(`value`): `value is Probability`
Defined in: [packages/distribution/src/probability.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability.ts#L9)
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`number`
## Returns
[Section titled “Returns”](#returns)
`value is Probability`
# isProbabilityVector
> **isProbabilityVector**(`values`): `values is ArrayLike`
Defined in: [packages/distribution/src/probability-vector.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-vector.ts#L16)
Whether every entry is a probability and the compensated total lies within `PROBABILITY_TABLE_SUM_TOLERANCE` of one. This is the rule `probabilityTableDistribution` applies to its masses, without building a distribution. A caller that rejects a vector throws its own error. Takes linear time and constant space.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
`ArrayLike`<`number`>
## Returns
[Section titled “Returns”](#returns)
`values is ArrayLike`
# logNormalDistribution
> **logNormalDistribution**(`parameters`): [`LogNormalDistribution`](/reference/knotkit/distribution/interfaces/lognormaldistribution/)
Defined in: [packages/distribution/src/log-normal-distribution.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L30)
Create a log-normal distribution from the parameters of its underlying normal distribution. Each draw uses two 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`LogNormalDistributionParameters`](/reference/knotkit/distribution/interfaces/lognormaldistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`LogNormalDistribution`](/reference/knotkit/distribution/interfaces/lognormaldistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported log mean or log standard deviation.
# median
> **median**(`values`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:135](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L135)
Exact median of a copy of `values`: the middle value, or the mean of the two middle values. The input is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_SAMPLE` when `values` is empty or holds a non-finite value.
# normalDistribution
> **normalDistribution**(`parameters`): [`NormalDistribution`](/reference/knotkit/distribution/interfaces/normaldistribution/)
Defined in: [packages/distribution/src/normal-distribution.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L31)
Create a normal distribution with finite location and positive scale within the exported bounds. Each draw uses two 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`NormalDistributionParameters`](/reference/knotkit/distribution/interfaces/normaldistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`NormalDistribution`](/reference/knotkit/distribution/interfaces/normaldistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported mean or standard deviation.
# pearsonCorrelation
> **pearsonCorrelation**(`first`, `second`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:263](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L263)
Pearson product-moment correlation coefficient, clamped to \[-1, 1] against floating-point overshoot.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### second
[Section titled “second”](#second)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_SAMPLE` when the lengths differ, a sample holds fewer than 2 values, or a value is non-finite; `ZERO_VARIANCE` when either sample is constant.
# poissonDistribution
> **poissonDistribution**(`__namedParameters`): [`PoissonDistribution`](/reference/knotkit/distribution/interfaces/poissondistribution/)
Defined in: [packages/distribution/src/poisson-distribution.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/poisson-distribution.ts#L29)
Construct a Poisson count distribution. Mean zero gives a point mass at zero.
Draws consume two 32-bit words for mean below 10, including zero, and a variable number for transformed rejection at or above mean 10.
## Parameters
[Section titled “Parameters”](#parameters)
### \_\_namedParameters
[Section titled “\_\_namedParameters”](#__namedparameters)
[`PoissonDistributionParameters`](/reference/knotkit/distribution/interfaces/poissondistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`PoissonDistribution`](/reference/knotkit/distribution/interfaces/poissondistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for an unsupported mean.
# probabilityTableDistribution
> **probabilityTableDistribution**(`__namedParameters`): [`ProbabilityTableDistribution`](/reference/knotkit/distribution/interfaces/probabilitytabledistribution/)
Defined in: [packages/distribution/src/probability-table-distribution.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-table-distribution.ts#L88)
Build a finite discrete distribution from strictly increasing finite values and the associated masses. The masses are preserved. The cumulative array ends at one for the final positive mass.
Construction takes O(n) time and space. Evaluation and quantiles take O(log n) time. Draws consume two 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### \_\_namedParameters
[Section titled “\_\_namedParameters”](#__namedparameters)
[`ProbabilityTableDistributionParameters`](/reference/knotkit/distribution/interfaces/probabilitytabledistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`ProbabilityTableDistribution`](/reference/knotkit/distribution/interfaces/probabilitytabledistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_TABLE` for invalid rows or total mass.
# sampleMean
> **sampleMean**(`values`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:110](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L110)
Arithmetic mean, computed as a running mean so large values cannot overflow the sum.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_SAMPLE` when `values` is empty or holds a non-finite value.
# sampleQuantile
> **sampleQuantile**(`values`, `probability`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L147)
Quantile by linear interpolation between order statistics (Hyndman and Fan type 7, the default of NumPy, SciPy, and R). The input is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### probability
[Section titled “probability”](#probability)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_SAMPLE` when `values` is empty or holds a non-finite value; `INVALID_PROBABILITY` when `probability` is outside \[0, 1].
# sampleVariance
> **sampleVariance**(`values`, `options?`): `number`
Defined in: [packages/distribution/src/sample-statistics.ts:122](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L122)
Variance by Welford’s one-pass algorithm. The divisor is `length - degreesOfFreedomCorrection`, so the default `1` is the unbiased sample variance and `0` is the population variance.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
[`NumericSample`](/reference/knotkit/distribution/type-aliases/numericsample/)
### options?
[Section titled “options?”](#options)
[`SampleMomentOptions`](/reference/knotkit/distribution/interfaces/samplemomentoptions/)
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_PARAMETER` when the correction is not a nonnegative integer; `INVALID_SAMPLE` when `values` holds a non-finite value or no more than `degreesOfFreedomCorrection` values.
# studentTDistribution
> **studentTDistribution**(`parameters`): [`StudentTDistribution`](/reference/knotkit/distribution/interfaces/studenttdistribution/)
Defined in: [packages/distribution/src/student-t-distribution.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L34)
Create a Student’s t distribution with the given degrees of freedom. One degree of freedom is the Cauchy distribution. Tails use the regularized incomplete beta function. Each draw divides a normal draw by the square root of a scaled chi-squared draw and consumes a variable number of 32-bit words.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`StudentTDistributionParameters`](/reference/knotkit/distribution/interfaces/studenttdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`StudentTDistribution`](/reference/knotkit/distribution/interfaces/studenttdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for unsupported degrees of freedom.
# uniformDistribution
> **uniformDistribution**(`parameters`): [`UniformDistribution`](/reference/knotkit/distribution/interfaces/uniformdistribution/)
Defined in: [packages/distribution/src/uniform-distribution.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/uniform-distribution.ts#L33)
Create a uniform distribution on a finite interval. Draws use two 32-bit words and exclude the upper bound.
## Parameters
[Section titled “Parameters”](#parameters)
### parameters
[Section titled “parameters”](#parameters-1)
[`UniformDistributionParameters`](/reference/knotkit/distribution/interfaces/uniformdistributionparameters/)
## Returns
[Section titled “Returns”](#returns)
[`UniformDistribution`](/reference/knotkit/distribution/interfaces/uniformdistribution/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PARAMETER` for non-finite or unordered bounds.
# BetaDistribution
Defined in: [packages/distribution/src/beta-distribution.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L20)
A beta distribution on the closed unit interval.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"beta"`, [`BetaDistributionParameters`](/reference/knotkit/distribution/interfaces/betadistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"beta"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# BetaDistributionParameters
Defined in: [packages/distribution/src/beta-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L14)
The two positive shapes of a beta distribution.
## Properties
[Section titled “Properties”](#properties)
### alpha
[Section titled “alpha”](#alpha)
> `readonly` **alpha**: `number`
Defined in: [packages/distribution/src/beta-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L15)
***
### beta
[Section titled “beta”](#beta)
> `readonly` **beta**: `number`
Defined in: [packages/distribution/src/beta-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L16)
# BinomialDistribution
Defined in: [packages/distribution/src/binomial-distribution.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L21)
The count of successes in independent Bernoulli trials.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"binomial"`, [`BinomialDistributionParameters`](/reference/knotkit/distribution/interfaces/binomialdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binomial"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# BinomialDistributionParameters
Defined in: [packages/distribution/src/binomial-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L13)
## Properties
[Section titled “Properties”](#properties)
### trials
[Section titled “trials”](#trials)
> `readonly` **trials**: `number`
Defined in: [packages/distribution/src/binomial-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L15)
Number of independent trials, from zero through `BINOMIAL_MAX_TRIALS`.
***
### successProbability
[Section titled “successProbability”](#successprobability)
> `readonly` **successProbability**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/binomial-distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L17)
The common success probability of each trial.
# ChiSquaredDistribution
Defined in: [packages/distribution/src/chi-squared-distribution.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L18)
A chi-squared distribution on the nonnegative real line.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"chi-squared"`, [`ChiSquaredDistributionParameters`](/reference/knotkit/distribution/interfaces/chisquareddistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"chi-squared"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# ChiSquaredDistributionParameters
Defined in: [packages/distribution/src/chi-squared-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L13)
Positive degrees of freedom, which can be fractional.
## Properties
[Section titled “Properties”](#properties)
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/distribution/src/chi-squared-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L14)
# ContinuousDistribution
Defined in: [packages/distribution/src/distribution.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L60)
A distribution with a density over an interval.
## Extends
[Section titled “Extends”](#extends)
* [`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/)<`K`, `P`>
## Extended by
[Section titled “Extended by”](#extended-by)
* [`NormalDistribution`](/reference/knotkit/distribution/interfaces/normaldistribution/)
* [`LogNormalDistribution`](/reference/knotkit/distribution/interfaces/lognormaldistribution/)
* [`GammaDistribution`](/reference/knotkit/distribution/interfaces/gammadistribution/)
* [`ExponentialDistribution`](/reference/knotkit/distribution/interfaces/exponentialdistribution/)
* [`ChiSquaredDistribution`](/reference/knotkit/distribution/interfaces/chisquareddistribution/)
* [`BetaDistribution`](/reference/knotkit/distribution/interfaces/betadistribution/)
* [`StudentTDistribution`](/reference/knotkit/distribution/interfaces/studenttdistribution/)
* [`FDistribution`](/reference/knotkit/distribution/interfaces/fdistribution/)
* [`UniformDistribution`](/reference/knotkit/distribution/interfaces/uniformdistribution/)
* [`CustomContinuousDistribution`](/reference/knotkit/distribution/interfaces/customcontinuousdistribution/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K` *extends* `string` = `string`
### P
[Section titled “P”](#p)
`P` *extends* `object` = `object`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `K`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`support`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
# ContinuousDistributionParametersByKind
Defined in: [packages/distribution/src/layouts.ts:131](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L131)
## Properties
[Section titled “Properties”](#properties)
### normal
[Section titled “normal”](#normal)
> `readonly` **normal**: [`NormalDistributionParameters`](/reference/knotkit/distribution/interfaces/normaldistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:132](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L132)
***
### log-normal
[Section titled “log-normal”](#log-normal)
> `readonly` **log-normal**: [`LogNormalDistributionParameters`](/reference/knotkit/distribution/interfaces/lognormaldistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L133)
***
### gamma
[Section titled “gamma”](#gamma)
> `readonly` **gamma**: [`GammaDistributionParameters`](/reference/knotkit/distribution/interfaces/gammadistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:134](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L134)
***
### exponential
[Section titled “exponential”](#exponential)
> `readonly` **exponential**: [`ExponentialDistributionParameters`](/reference/knotkit/distribution/interfaces/exponentialdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:135](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L135)
***
### chi-squared
[Section titled “chi-squared”](#chi-squared)
> `readonly` **chi-squared**: [`ChiSquaredDistributionParameters`](/reference/knotkit/distribution/interfaces/chisquareddistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L136)
***
### beta
[Section titled “beta”](#beta)
> `readonly` **beta**: [`BetaDistributionParameters`](/reference/knotkit/distribution/interfaces/betadistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:137](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L137)
***
### student-t
[Section titled “student-t”](#student-t)
> `readonly` **student-t**: [`StudentTDistributionParameters`](/reference/knotkit/distribution/interfaces/studenttdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:138](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L138)
***
### f
[Section titled “f”](#f)
> `readonly` **f**: [`FDistributionParameters`](/reference/knotkit/distribution/interfaces/fdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:139](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L139)
***
### uniform
[Section titled “uniform”](#uniform)
> `readonly` **uniform**: [`UniformDistributionParameters`](/reference/knotkit/distribution/interfaces/uniformdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:140](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L140)
# CumulativeDistribution
Defined in: [packages/distribution/src/distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L11)
The shared operations of discrete and continuous distributions.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K` *extends* `string` = `string`
### P
[Section titled “P”](#p)
`P` *extends* `object` = `object`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `K`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
# CustomContinuousDistribution
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L16)
A distribution with a density over an interval.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"custom-continuous"`, [`CustomContinuousDistributionParameters`](/reference/knotkit/distribution/interfaces/customcontinuousdistributionparameters/)>
## Properties
[Section titled “Properties”](#properties)
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L21)
#### Parameters
[Section titled “Parameters”](#parameters)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns)
`number`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_CALLBACK_VALUE`, or `QUANTILE_NOT_BRACKETED`.
#### Overrides
[Section titled “Overrides”](#overrides)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"custom-continuous"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters-1)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
# CustomContinuousDistributionParameters
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L7)
## Properties
[Section titled “Properties”](#properties)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
> `readonly` **lowerBound**: `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L8)
***
### upperBound
[Section titled “upperBound”](#upperbound)
> `readonly` **upperBound**: `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L9)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`value`) => `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L10)
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns)
`number`
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`value`) => `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L11)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
***
### survivalProbability?
[Section titled “survivalProbability?”](#survivalprobability)
> `readonly` `optional` **survivalProbability?**: (`value`) => `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L12)
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
***
### quantile?
[Section titled “quantile?”](#quantile)
> `readonly` `optional` **quantile?**: (`p`) => `number`
Defined in: [packages/distribution/src/custom-continuous-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-continuous-distribution.ts#L13)
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
# CustomDiscreteDistribution
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L15)
A distribution assigning probability masses to individual outcomes.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"custom-discrete"`, [`CustomDiscreteDistributionParameters`](/reference/knotkit/distribution/interfaces/customdiscretedistributionparameters/)>
## Properties
[Section titled “Properties”](#properties)
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L20)
#### Parameters
[Section titled “Parameters”](#parameters)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns)
`number`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_CALLBACK_VALUE`, or `QUANTILE_NOT_BRACKETED`.
#### Overrides
[Section titled “Overrides”](#overrides)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"custom-discrete"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters-1)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
# CustomDiscreteDistributionParameters
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L8)
## Properties
[Section titled “Properties”](#properties)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
> `readonly` **lowerBound**: `number`
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L9)
***
### upperBound
[Section titled “upperBound”](#upperbound)
> `readonly` **upperBound**: `number`
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L10)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`value`) => `number`
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L11)
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns)
`number`
***
### cumulativeProbability?
[Section titled “cumulativeProbability?”](#cumulativeprobability)
> `readonly` `optional` **cumulativeProbability?**: (`value`) => `number`
Defined in: [packages/distribution/src/custom-discrete-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/custom-discrete-distribution.ts#L12)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
# CustomDistributionParametersByKind
Defined in: [packages/distribution/src/layouts.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L180)
## Properties
[Section titled “Properties”](#properties)
### custom-discrete
[Section titled “custom-discrete”](#custom-discrete)
> `readonly` **custom-discrete**: [`CustomDiscreteDistributionParameters`](/reference/knotkit/distribution/interfaces/customdiscretedistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:181](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L181)
***
### custom-continuous
[Section titled “custom-continuous”](#custom-continuous)
> `readonly` **custom-continuous**: [`CustomContinuousDistributionParameters`](/reference/knotkit/distribution/interfaces/customcontinuousdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:182](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L182)
# DiscreteDistribution
Defined in: [packages/distribution/src/distribution.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L43)
A distribution assigning probability masses to individual outcomes.
## Extends
[Section titled “Extends”](#extends)
* [`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/)<`K`, `P`>
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BinomialDistribution`](/reference/knotkit/distribution/interfaces/binomialdistribution/)
* [`GeometricDistribution`](/reference/knotkit/distribution/interfaces/geometricdistribution/)
* [`HypergeometricDistribution`](/reference/knotkit/distribution/interfaces/hypergeometricdistribution/)
* [`PoissonDistribution`](/reference/knotkit/distribution/interfaces/poissondistribution/)
* [`ProbabilityTableDistribution`](/reference/knotkit/distribution/interfaces/probabilitytabledistribution/)
* [`CustomDiscreteDistribution`](/reference/knotkit/distribution/interfaces/customdiscretedistribution/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K` *extends* `string` = `string`
### P
[Section titled “P”](#p)
`P` *extends* `object` = `object`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `K`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`support`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CumulativeDistribution`](/reference/knotkit/distribution/interfaces/cumulativedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/cumulativedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
# DiscreteDistributionParametersByKind
Defined in: [packages/distribution/src/layouts.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L77)
## Properties
[Section titled “Properties”](#properties)
### poisson
[Section titled “poisson”](#poisson)
> `readonly` **poisson**: [`PoissonDistributionParameters`](/reference/knotkit/distribution/interfaces/poissondistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L78)
***
### binomial
[Section titled “binomial”](#binomial)
> `readonly` **binomial**: [`BinomialDistributionParameters`](/reference/knotkit/distribution/interfaces/binomialdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L79)
***
### geometric
[Section titled “geometric”](#geometric)
> `readonly` **geometric**: [`GeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/geometricdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L80)
***
### hypergeometric
[Section titled “hypergeometric”](#hypergeometric)
> `readonly` **hypergeometric**: [`HypergeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/hypergeometricdistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L81)
***
### probability-table
[Section titled “probability-table”](#probability-table)
> `readonly` **probability-table**: [`ProbabilityTableDistributionParameters`](/reference/knotkit/distribution/interfaces/probabilitytabledistributionparameters/)
Defined in: [packages/distribution/src/layouts.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L82)
# DistributionMoments
Defined in: [packages/distribution/src/distribution.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L77)
The moment operations provided by named distributions and probability tables.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BinomialDistribution`](/reference/knotkit/distribution/interfaces/binomialdistribution/)
* [`GeometricDistribution`](/reference/knotkit/distribution/interfaces/geometricdistribution/)
* [`HypergeometricDistribution`](/reference/knotkit/distribution/interfaces/hypergeometricdistribution/)
* [`PoissonDistribution`](/reference/knotkit/distribution/interfaces/poissondistribution/)
* [`NormalDistribution`](/reference/knotkit/distribution/interfaces/normaldistribution/)
* [`LogNormalDistribution`](/reference/knotkit/distribution/interfaces/lognormaldistribution/)
* [`GammaDistribution`](/reference/knotkit/distribution/interfaces/gammadistribution/)
* [`ExponentialDistribution`](/reference/knotkit/distribution/interfaces/exponentialdistribution/)
* [`ChiSquaredDistribution`](/reference/knotkit/distribution/interfaces/chisquareddistribution/)
* [`BetaDistribution`](/reference/knotkit/distribution/interfaces/betadistribution/)
* [`StudentTDistribution`](/reference/knotkit/distribution/interfaces/studenttdistribution/)
* [`FDistribution`](/reference/knotkit/distribution/interfaces/fdistribution/)
* [`UniformDistribution`](/reference/knotkit/distribution/interfaces/uniformdistribution/)
* [`ProbabilityTableDistribution`](/reference/knotkit/distribution/interfaces/probabilitytabledistribution/)
## Properties
[Section titled “Properties”](#properties)
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns)
`number`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
# DistributionSupport
Defined in: [packages/distribution/src/distribution.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L5)
The endpoints of a distribution’s support. An unbounded end is infinite.
## Properties
[Section titled “Properties”](#properties)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
> `readonly` **lowerBound**: `number`
Defined in: [packages/distribution/src/distribution.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L6)
***
### upperBound
[Section titled “upperBound”](#upperbound)
> `readonly` **upperBound**: `number`
Defined in: [packages/distribution/src/distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L7)
# ExponentialDistribution
Defined in: [packages/distribution/src/exponential-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L16)
An exponential distribution on the nonnegative real line.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"exponential"`, [`ExponentialDistributionParameters`](/reference/knotkit/distribution/interfaces/exponentialdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"exponential"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# ExponentialDistributionParameters
Defined in: [packages/distribution/src/exponential-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L11)
The positive rate of an exponential distribution.
## Properties
[Section titled “Properties”](#properties)
### rate
[Section titled “rate”](#rate)
> `readonly` **rate**: `number`
Defined in: [packages/distribution/src/exponential-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L12)
# FDistribution
Defined in: [packages/distribution/src/f-distribution.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L23)
An F distribution on the nonnegative real line. The mean is `Infinity` for `denominatorDegreesOfFreedom` up to 2. The variance is `Infinity` above 2 and up to 4, and `NaN` at or below 2. `rawMoment(order)` is `Infinity` once `order` reaches half the denominator degrees.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"f"`, [`FDistributionParameters`](/reference/knotkit/distribution/interfaces/fdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"f"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# FDistributionParameters
Defined in: [packages/distribution/src/f-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L13)
The two positive degrees of freedom of an F distribution, which can be fractional.
## Properties
[Section titled “Properties”](#properties)
### numeratorDegreesOfFreedom
[Section titled “numeratorDegreesOfFreedom”](#numeratordegreesoffreedom)
> `readonly` **numeratorDegreesOfFreedom**: `number`
Defined in: [packages/distribution/src/f-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L14)
***
### denominatorDegreesOfFreedom
[Section titled “denominatorDegreesOfFreedom”](#denominatordegreesoffreedom)
> `readonly` **denominatorDegreesOfFreedom**: `number`
Defined in: [packages/distribution/src/f-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L15)
# GammaDistribution
Defined in: [packages/distribution/src/gamma-distribution.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L21)
A gamma distribution on the nonnegative real line.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"gamma"`, [`GammaDistributionParameters`](/reference/knotkit/distribution/interfaces/gammadistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"gamma"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# GammaDistributionParameters
Defined in: [packages/distribution/src/gamma-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L15)
Shape and rate of a gamma distribution. The scale is the reciprocal of the rate.
## Properties
[Section titled “Properties”](#properties)
### shape
[Section titled “shape”](#shape)
> `readonly` **shape**: `number`
Defined in: [packages/distribution/src/gamma-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L16)
***
### rate
[Section titled “rate”](#rate)
> `readonly` **rate**: `number`
Defined in: [packages/distribution/src/gamma-distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L17)
# GeometricDistribution
Defined in: [packages/distribution/src/geometric-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/geometric-distribution.ts#L16)
The count of failures before the first success.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"geometric"`, [`GeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/geometricdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"geometric"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# GeometricDistributionParameters
Defined in: [packages/distribution/src/geometric-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/geometric-distribution.ts#L10)
## Properties
[Section titled “Properties”](#properties)
### successProbability
[Section titled “successProbability”](#successprobability)
> `readonly` **successProbability**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/geometric-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/geometric-distribution.ts#L12)
Success probability, from `GEOMETRIC_MIN_SUCCESS_PROBABILITY` through one.
# Histogram
Defined in: [packages/distribution/src/sample-statistics.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L33)
Counts per bin and the `counts.length + 1` edges that bound them.
## Properties
[Section titled “Properties”](#properties)
### counts
[Section titled “counts”](#counts)
> `readonly` **counts**: readonly `number`\[]
Defined in: [packages/distribution/src/sample-statistics.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L34)
***
### edges
[Section titled “edges”](#edges)
> `readonly` **edges**: readonly `number`\[]
Defined in: [packages/distribution/src/sample-statistics.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L35)
# HistogramBinsOptions
Defined in: [packages/distribution/src/sample-statistics.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L20)
Equal-width bins over the sample’s range.
## Properties
[Section titled “Properties”](#properties)
### bins
[Section titled “bins”](#bins)
> `readonly` **bins**: `number`
Defined in: [packages/distribution/src/sample-statistics.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L21)
# HistogramEdgesOptions
Defined in: [packages/distribution/src/sample-statistics.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L25)
Explicit, strictly increasing bin edges.
## Properties
[Section titled “Properties”](#properties)
### edges
[Section titled “edges”](#edges)
> `readonly` **edges**: readonly `number`\[]
Defined in: [packages/distribution/src/sample-statistics.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L26)
# HypergeometricDistribution
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L27)
The count of successes in draws without replacement.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"hypergeometric"`, [`HypergeometricDistributionParameters`](/reference/knotkit/distribution/interfaces/hypergeometricdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hypergeometric"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# HypergeometricDistributionParameters
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L17)
## Properties
[Section titled “Properties”](#properties)
### populationSize
[Section titled “populationSize”](#populationsize)
> `readonly` **populationSize**: `number`
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L19)
Number of items in the population, through `HYPERGEOMETRIC_MAX_POPULATION_SIZE`.
***
### successCount
[Section titled “successCount”](#successcount)
> `readonly` **successCount**: `number`
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L21)
Number of successes in the population, from zero through its size.
***
### sampleSize
[Section titled “sampleSize”](#samplesize)
> `readonly` **sampleSize**: `number`
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L23)
Number of draws without replacement, from zero through the population size.
# LogNormalDistribution
Defined in: [packages/distribution/src/log-normal-distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L22)
A log-normal distribution on the positive real line.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"log-normal"`, [`LogNormalDistributionParameters`](/reference/knotkit/distribution/interfaces/lognormaldistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"log-normal"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# LogNormalDistributionParameters
Defined in: [packages/distribution/src/log-normal-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L16)
Location and positive scale after taking the natural logarithm.
## Properties
[Section titled “Properties”](#properties)
### logMean
[Section titled “logMean”](#logmean)
> `readonly` **logMean**: `number`
Defined in: [packages/distribution/src/log-normal-distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L17)
***
### logStandardDeviation
[Section titled “logStandardDeviation”](#logstandarddeviation)
> `readonly` **logStandardDeviation**: `number`
Defined in: [packages/distribution/src/log-normal-distribution.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L18)
# NormalDistribution
Defined in: [packages/distribution/src/normal-distribution.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L23)
A normal distribution on the real line.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"normal"`, [`NormalDistributionParameters`](/reference/knotkit/distribution/interfaces/normaldistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"normal"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# NormalDistributionParameters
Defined in: [packages/distribution/src/normal-distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L17)
Location and positive scale of a normal distribution.
## Properties
[Section titled “Properties”](#properties)
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/normal-distribution.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L18)
***
### standardDeviation
[Section titled “standardDeviation”](#standarddeviation)
> `readonly` **standardDeviation**: `number`
Defined in: [packages/distribution/src/normal-distribution.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L19)
# PoissonDistribution
Defined in: [packages/distribution/src/poisson-distribution.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/poisson-distribution.ts#L18)
A Poisson count distribution.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"poisson"`, [`PoissonDistributionParameters`](/reference/knotkit/distribution/interfaces/poissondistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"poisson"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# PoissonDistributionParameters
Defined in: [packages/distribution/src/poisson-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/poisson-distribution.ts#L12)
## Properties
[Section titled “Properties”](#properties)
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/poisson-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/poisson-distribution.ts#L14)
Expected count, from zero through `POISSON_MAX_MEAN`.
# ProbabilityTableDistribution
Defined in: [packages/distribution/src/probability-table-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-table-distribution.ts#L14)
A distribution assigning probability masses to individual outcomes.
## Extends
[Section titled “Extends”](#extends)
* [`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/)<`"probability-table"`, [`ProbabilityTableDistributionParameters`](/reference/knotkit/distribution/interfaces/probabilitytabledistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"probability-table"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`kind`](/reference/knotkit/distribution/interfaces/discretedistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/discretedistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`support`](/reference/knotkit/distribution/interfaces/discretedistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/discretedistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`draw`](/reference/knotkit/distribution/interfaces/discretedistribution/#draw)
***
### probability
[Section titled “probability”](#probability)
> `readonly` **probability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L51)
The probability of the outcome `x`, or 0 if `x` is absent from the support.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`probability`](/reference/knotkit/distribution/interfaces/discretedistribution/#probability)
***
### logProbability
[Section titled “logProbability”](#logprobability)
> `readonly` **logProbability**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L56)
The natural logarithm of the probability of `x`, with `-Infinity` for zero mass.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`DiscreteDistribution`](/reference/knotkit/distribution/interfaces/discretedistribution/).[`logProbability`](/reference/knotkit/distribution/interfaces/discretedistribution/#logprobability)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# ProbabilityTableDistributionParameters
Defined in: [packages/distribution/src/probability-table-distribution.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-table-distribution.ts#L9)
## Properties
[Section titled “Properties”](#properties)
### values
[Section titled “values”](#values)
> `readonly` **values**: readonly `number`\[]
Defined in: [packages/distribution/src/probability-table-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-table-distribution.ts#L10)
***
### probabilities
[Section titled “probabilities”](#probabilities)
> `readonly` **probabilities**: readonly [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)\[]
Defined in: [packages/distribution/src/probability-table-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-table-distribution.ts#L11)
# SampleMomentOptions
Defined in: [packages/distribution/src/sample-statistics.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L14)
Options for sample moments that divide by `length - degreesOfFreedomCorrection`.
## Properties
[Section titled “Properties”](#properties)
### degreesOfFreedomCorrection?
[Section titled “degreesOfFreedomCorrection?”](#degreesoffreedomcorrection)
> `readonly` `optional` **degreesOfFreedomCorrection?**: `number`
Defined in: [packages/distribution/src/sample-statistics.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L16)
Subtracted from the sample length in the divisor. Defaults to `1`; use `0` for the population form.
# StudentTDistribution
Defined in: [packages/distribution/src/student-t-distribution.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L25)
A Student’s t distribution on the real line. The mean is 0 above one degree of freedom and `NaN` otherwise. The variance is `degreesOfFreedom / (degreesOfFreedom - 2)` above two, `Infinity` up to two and `NaN` at or below one. `rawMoment(order)` is 0 for an odd order below the degrees of freedom, `Infinity` for an even order at or above them and `NaN` for an odd order at or above them.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"student-t"`, [`StudentTDistributionParameters`](/reference/knotkit/distribution/interfaces/studenttdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"student-t"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# StudentTDistributionParameters
Defined in: [packages/distribution/src/student-t-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L15)
Positive degrees of freedom, which can be fractional.
## Properties
[Section titled “Properties”](#properties)
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/distribution/src/student-t-distribution.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L16)
# UniformDistribution
Defined in: [packages/distribution/src/uniform-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/uniform-distribution.ts#L13)
A uniform distribution on a nonempty finite interval.
## Extends
[Section titled “Extends”](#extends)
* [`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)<`"uniform"`, [`UniformDistributionParameters`](/reference/knotkit/distribution/interfaces/uniformdistributionparameters/)>
* [`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"uniform"`
Defined in: [packages/distribution/src/distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L13)
The serializable name of the family.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`kind`](/reference/knotkit/distribution/interfaces/continuousdistribution/#kind)
***
### parameters
[Section titled “parameters”](#parameters)
> `readonly` **parameters**: `Readonly`<`P`>
Defined in: [packages/distribution/src/distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L15)
The captured input parameters.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`parameters`](/reference/knotkit/distribution/interfaces/continuousdistribution/#parameters)
***
### support
[Section titled “support”](#support)
> `readonly` **support**: [`DistributionSupport`](/reference/knotkit/distribution/interfaces/distributionsupport/)
Defined in: [packages/distribution/src/distribution.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L17)
The closed bounds of the represented outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`support`](/reference/knotkit/distribution/interfaces/continuousdistribution/#support)
***
### cumulativeProbability
[Section titled “cumulativeProbability”](#cumulativeprobability)
> `readonly` **cumulativeProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L22)
The probability of an outcome at or below `x`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### x
[Section titled “x”](#x)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`cumulativeProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#cumulativeprobability)
***
### survivalProbability
[Section titled “survivalProbability”](#survivalprobability)
> `readonly` **survivalProbability**: (`x`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/distribution/src/distribution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L27)
The probability of an outcome strictly above `x`.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### x
[Section titled “x”](#x-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`survivalProbability`](/reference/knotkit/distribution/interfaces/continuousdistribution/#survivalprobability)
***
### quantile
[Section titled “quantile”](#quantile)
> `readonly` **quantile**: (`p`) => `number`
Defined in: [packages/distribution/src/distribution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L32)
The first support value whose cumulative probability reaches `p`. At 0 and 1, returns the support endpoints.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### p
[Section titled “p”](#p)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_PROBABILITY` when `p` is outside \[0, 1] or is `NaN`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`quantile`](/reference/knotkit/distribution/interfaces/continuousdistribution/#quantile)
***
### draw
[Section titled “draw”](#draw)
> `readonly` **draw**: (`random`) => `number`
Defined in: [packages/distribution/src/distribution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L39)
Draw one value from the supplied source. There is no state between draws besides the caller’s source. The same seed replays on the same engine build and platform. One differing comparison or rounding on another engine can change that draw and every later one, including how many words a rejection sampler consumes.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_SOURCE_VALUE` for an invalid value from the source.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`draw`](/reference/knotkit/distribution/interfaces/continuousdistribution/#draw)
***
### density
[Section titled “density”](#density)
> `readonly` **density**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L68)
The density at `x`, with zero outside the support and the interior limit at a finite endpoint.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### x
[Section titled “x”](#x-2)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`density`](/reference/knotkit/distribution/interfaces/continuousdistribution/#density)
***
### logDensity
[Section titled “logDensity”](#logdensity)
> `readonly` **logDensity**: (`x`) => `number`
Defined in: [packages/distribution/src/distribution.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L73)
The natural logarithm of the density at `x`, with `-Infinity` for zero density.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### x
[Section titled “x”](#x-3)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`number`
#### Throws
[Section titled “Throws”](#throws-5)
With `INVALID_ARGUMENT` when `x` is `NaN` or not a number.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/).[`logDensity`](/reference/knotkit/distribution/interfaces/continuousdistribution/#logdensity)
***
### mean
[Section titled “mean”](#mean)
> `readonly` **mean**: `number`
Defined in: [packages/distribution/src/distribution.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L79)
The expected value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`mean`](/reference/knotkit/distribution/interfaces/distributionmoments/#mean)
***
### variance
[Section titled “variance”](#variance)
> `readonly` **variance**: `number`
Defined in: [packages/distribution/src/distribution.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L81)
The expected squared deviation from the mean.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`variance`](/reference/knotkit/distribution/interfaces/distributionmoments/#variance)
***
### rawMoment
[Section titled “rawMoment”](#rawmoment)
> `readonly` **rawMoment**: (`order`) => `number`
Defined in: [packages/distribution/src/distribution.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/distribution.ts#L86)
The expected value of the outcome raised to `order`. The zeroth moment is 1.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### order
[Section titled “order”](#order)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With `INVALID_MOMENT_ORDER` outside the supported integer orders.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`DistributionMoments`](/reference/knotkit/distribution/interfaces/distributionmoments/).[`rawMoment`](/reference/knotkit/distribution/interfaces/distributionmoments/#rawmoment)
# UniformDistributionParameters
Defined in: [packages/distribution/src/uniform-distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/uniform-distribution.ts#L7)
The ordered finite endpoints of a uniform distribution.
## Properties
[Section titled “Properties”](#properties)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
> `readonly` **lowerBound**: `number`
Defined in: [packages/distribution/src/uniform-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/uniform-distribution.ts#L8)
***
### upperBound
[Section titled “upperBound”](#upperbound)
> `readonly` **upperBound**: `number`
Defined in: [packages/distribution/src/uniform-distribution.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/uniform-distribution.ts#L9)
# ContinuousDistributionKind
> **ContinuousDistributionKind** = *typeof* [`CONTINUOUS_DISTRIBUTION_KINDS`](/reference/knotkit/distribution/variables/continuous_distribution_kinds/)\[`number`]
Defined in: [packages/distribution/src/layouts.ts:129](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L129)
# CustomDistributionKind
> **CustomDistributionKind** = *typeof* [`CUSTOM_DISTRIBUTION_KINDS`](/reference/knotkit/distribution/variables/custom_distribution_kinds/)\[`number`]
Defined in: [packages/distribution/src/layouts.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L178)
# DiscreteDistributionKind
> **DiscreteDistributionKind** = *typeof* [`DISCRETE_DISTRIBUTION_KINDS`](/reference/knotkit/distribution/variables/discrete_distribution_kinds/)\[`number`]
Defined in: [packages/distribution/src/layouts.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L75)
# DistributionErrorCode
> **DistributionErrorCode** = [`DistributionInvalidInputErrorCode`](/reference/knotkit/distribution/type-aliases/distributioninvalidinputerrorcode/)
Defined in: [packages/distribution/src/errors.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L24)
A machine-readable error code emitted by `knotkit/distribution`.
# DistributionInvalidInputErrorCode
> **DistributionInvalidInputErrorCode** = *typeof* [`DISTRIBUTION_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/distribution/variables/distribution_invalid_input_error_codes/)\[`number`]
Defined in: [packages/distribution/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L21)
A machine-readable invalid-input code emitted by `knotkit/distribution`.
# HistogramOptions
> **HistogramOptions** = [`HistogramBinsOptions`](/reference/knotkit/distribution/interfaces/histogrambinsoptions/) | [`HistogramEdgesOptions`](/reference/knotkit/distribution/interfaces/histogramedgesoptions/)
Defined in: [packages/distribution/src/sample-statistics.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/sample-statistics.ts#L30)
How `histogram` places its bins.
# NumericSample
> **NumericSample** = `ArrayLike`<`number`>
Defined in: [packages/distribution/src/internal/sample.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/internal/sample.ts#L5)
A dense numeric array or typed array of observations.
# Probability
> **Probability** = `number` & `object`
Defined in: [packages/distribution/src/probability.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability.ts#L7)
A number in the closed unit interval, checked by [Probability.make](/reference/knotkit/distribution/variables/probability/#make).
## Type Declaration
[Section titled “Type Declaration”](#type-declaration)
### \[probabilityBrand]
[Section titled “\[probabilityBrand\]”](#probabilitybrand)
> `readonly` **\[probabilityBrand]**: `true`
# BETA_MAX_SHAPE
> `const` **BETA_MAX_SHAPE**: `100000` = `1e5`
Defined in: [packages/distribution/src/beta-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L11)
# BETA_MIN_SHAPE
> `const` **BETA_MIN_SHAPE**: `0.001` = `0.001`
Defined in: [packages/distribution/src/beta-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/beta-distribution.ts#L10)
The supported range of each beta shape.
# BINOMIAL_MAX_TRIALS
> `const` **BINOMIAL_MAX_TRIALS**: `200000` = `200_000`
Defined in: [packages/distribution/src/binomial-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/binomial-distribution.ts#L11)
The largest supported binomial trial count.
# CHI_SQUARED_MAX_DEGREES_OF_FREEDOM
> `const` **CHI_SQUARED_MAX_DEGREES_OF_FREEDOM**: `number`
Defined in: [packages/distribution/src/chi-squared-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L10)
The largest supported degrees of freedom.
# CHI_SQUARED_MIN_DEGREES_OF_FREEDOM
> `const` **CHI_SQUARED_MIN_DEGREES_OF_FREEDOM**: `number`
Defined in: [packages/distribution/src/chi-squared-distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/chi-squared-distribution.ts#L7)
The smallest supported positive degrees of freedom.
# CONTINUOUS_DISTRIBUTION_KINDS
> `const` **CONTINUOUS_DISTRIBUTION_KINDS**: readonly \[`"normal"`, `"log-normal"`, `"gamma"`, `"exponential"`, `"chi-squared"`, `"beta"`, `"student-t"`, `"f"`, `"uniform"`]
Defined in: [packages/distribution/src/layouts.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L107)
The continuous distribution families in the order used by the construction table.
# __CONTINUOUS_DISTRIBUTION_LAYOUTS
> `const` **\_\_CONTINUOUS_DISTRIBUTION_LAYOUTS**: `{ readonly [Kind in ContinuousDistributionKind]: (parameters: Readonly) => ContinuousDistributionByKind[Kind] }`
Defined in: [packages/distribution/src/layouts.ts:156](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L156)
Construct each continuous family from the same parameter shape it returns.
# CUSTOM_DISTRIBUTION_KINDS
> `const` **CUSTOM_DISTRIBUTION_KINDS**: readonly \[`"custom-discrete"`, `"custom-continuous"`]
Defined in: [packages/distribution/src/layouts.ts:173](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L173)
Families with callback parameters supplied by the caller.
# __CUSTOM_DISTRIBUTION_LAYOUTS
> `const` **\_\_CUSTOM_DISTRIBUTION_LAYOUTS**: `{ readonly [Kind in CustomDistributionKind]: (parameters: Readonly) => CustomDistributionByKind[Kind] }`
Defined in: [packages/distribution/src/layouts.ts:191](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L191)
Construct a distribution from callback parameters in memory.
# DISCRETE_DISTRIBUTION_KINDS
> `const` **DISCRETE_DISTRIBUTION_KINDS**: readonly \[`"poisson"`, `"binomial"`, `"geometric"`, `"hypergeometric"`, `"probability-table"`]
Defined in: [packages/distribution/src/layouts.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L67)
The discrete distribution families in the order used by the construction table.
# __DISCRETE_DISTRIBUTION_LAYOUTS
> `const` **\_\_DISCRETE_DISTRIBUTION_LAYOUTS**: `{ readonly [Kind in DiscreteDistributionKind]: (parameters: Readonly) => DiscreteDistributionByKind[Kind] }`
Defined in: [packages/distribution/src/layouts.ts:94](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/layouts.ts#L94)
Construct each discrete family from the same parameter shape it returns.
# DISTRIBUTION_ERROR_CODES
> `const` **DISTRIBUTION_ERROR_CODES**: *typeof* [`DISTRIBUTION_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/distribution/variables/distribution_invalid_input_error_codes/) = `DISTRIBUTION_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/distribution/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L17)
Every machine-readable error code emitted by `knotkit/distribution`.
# DISTRIBUTION_INVALID_INPUT_ERROR_CODES
> `const` **DISTRIBUTION_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_PARAMETER"`, `"INVALID_ARGUMENT"`, `"INVALID_PROBABILITY"`, `"INVALID_MOMENT_ORDER"`, `"INVALID_TABLE"`, `"INVALID_CALLBACK_VALUE"`, `"QUANTILE_NOT_BRACKETED"`, `"INVALID_SAMPLE"`, `"ZERO_VARIANCE"`]
Defined in: [packages/distribution/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/errors.ts#L4)
The canonical, ordered list of input error codes emitted by `knotkit/distribution`.
# DISTRIBUTION_MAX_MOMENT_ORDER
> `const` **DISTRIBUTION_MAX_MOMENT_ORDER**: `64` = `64`
Defined in: [packages/distribution/src/internal/members/checks.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/internal/members/checks.ts#L6)
The maximum order accepted by distribution moment calculations.
# EXPONENTIAL_MAX_RATE
> `const` **EXPONENTIAL_MAX_RATE**: `number` = `MAX_RATE`
Defined in: [packages/distribution/src/exponential-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L8)
# EXPONENTIAL_MIN_RATE
> `const` **EXPONENTIAL_MIN_RATE**: `number` = `MIN_RATE`
Defined in: [packages/distribution/src/exponential-distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/exponential-distribution.ts#L7)
The supported positive rates.
# F_MAX_DEGREES_OF_FREEDOM
> `const` **F\_MAX_DEGREES_OF_FREEDOM**: `100000` = `1e5`
Defined in: [packages/distribution/src/f-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L10)
# F_MIN_DEGREES_OF_FREEDOM
> `const` **F\_MIN_DEGREES_OF_FREEDOM**: `0.1` = `0.1`
Defined in: [packages/distribution/src/f-distribution.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/f-distribution.ts#L9)
The supported range of each degrees-of-freedom parameter.
# GAMMA_MAX_RATE
> `const` **GAMMA_MAX_RATE**: `number` = `MAX_RATE`
Defined in: [packages/distribution/src/gamma-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L12)
# GAMMA_MAX_SHAPE
> `const` **GAMMA_MAX_SHAPE**: `100000` = `1e5`
Defined in: [packages/distribution/src/gamma-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L8)
# GAMMA_MIN_RATE
> `const` **GAMMA_MIN_RATE**: `number` = `MIN_RATE`
Defined in: [packages/distribution/src/gamma-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L11)
The supported positive rates.
# GAMMA_MIN_SHAPE
> `const` **GAMMA_MIN_SHAPE**: `0.001` = `0.001`
Defined in: [packages/distribution/src/gamma-distribution.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/gamma-distribution.ts#L7)
The supported shape range includes small, highly skewed gamma distributions.
# GEOMETRIC_MIN_SUCCESS_PROBABILITY
> `const` **GEOMETRIC_MIN_SUCCESS_PROBABILITY**: `1e-8` = `1e-8`
Defined in: [packages/distribution/src/geometric-distribution.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/geometric-distribution.ts#L8)
The smallest supported geometric success probability.
# HYPERGEOMETRIC_MAX_POPULATION_SIZE
> `const` **HYPERGEOMETRIC_MAX_POPULATION_SIZE**: `100000` = `100_000`
Defined in: [packages/distribution/src/hypergeometric-distribution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/hypergeometric-distribution.ts#L15)
The largest supported hypergeometric population size.
# LOG_NORMAL_MAX_ABSOLUTE_LOG_MEAN
> `const` **LOG_NORMAL_MAX_ABSOLUTE_LOG_MEAN**: `100` = `100`
Defined in: [packages/distribution/src/log-normal-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L10)
The maximum absolute mean of the underlying normal distribution.
# LOG_NORMAL_MAX_LOG_STANDARD_DEVIATION
> `const` **LOG_NORMAL_MAX_LOG_STANDARD_DEVIATION**: `10` = `10`
Defined in: [packages/distribution/src/log-normal-distribution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/log-normal-distribution.ts#L13)
The maximum standard deviation of the underlying normal distribution.
# NORMAL_MAX_ABSOLUTE_MEAN
> `const` **NORMAL_MAX_ABSOLUTE_MEAN**: `1000000` = `1e6`
Defined in: [packages/distribution/src/normal-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L11)
The maximum absolute normal mean.
# NORMAL_MAX_STANDARD_DEVIATION
> `const` **NORMAL_MAX_STANDARD_DEVIATION**: `1000000` = `1e6`
Defined in: [packages/distribution/src/normal-distribution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/normal-distribution.ts#L14)
The maximum normal standard deviation.
# POISSON_MAX_MEAN
> `const` **POISSON_MAX_MEAN**: `100000` = `100_000`
Defined in: [packages/distribution/src/poisson-distribution.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/poisson-distribution.ts#L10)
The largest supported Poisson mean.
# Probability
> **Probability**: `object`
Defined in: [packages/distribution/src/probability.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability.ts#L7)
Checked constructor for the opaque [Probability](/reference/knotkit/distribution/variables/probability/) scalar.
## Type Declaration
[Section titled “Type Declaration”](#type-declaration)
### make
[Section titled “make”](#make)
> `readonly` **make**: (`value`) => [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY` outside the closed unit interval.
# PROBABILITY_TABLE_SUM_TOLERANCE
> `const` **PROBABILITY_TABLE_SUM_TOLERANCE**: `1e-12` = `1e-12`
Defined in: [packages/distribution/src/probability-vector.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/probability-vector.ts#L5)
Maximum absolute deviation of the supplied total mass from one.
# STUDENT_T_MAX_DEGREES_OF_FREEDOM
> `const` **STUDENT_T_MAX_DEGREES_OF_FREEDOM**: `100000` = `1e5`
Defined in: [packages/distribution/src/student-t-distribution.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L12)
# STUDENT_T_MIN_DEGREES_OF_FREEDOM
> `const` **STUDENT_T_MIN_DEGREES_OF_FREEDOM**: `0.1` = `0.1`
Defined in: [packages/distribution/src/student-t-distribution.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/distribution/src/student-t-distribution.ts#L11)
The supported range of the degrees of freedom.
# knotkit/e-graph
## Classes
[Section titled “Classes”](#classes)
* [EGraphInvalidInputError](/reference/knotkit/e-graph/classes/egraphinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [EGraphExpression](/reference/knotkit/e-graph/interfaces/egraphexpression/)
* [EClass](/reference/knotkit/e-graph/interfaces/eclass/)
* [EGraph](/reference/knotkit/e-graph/interfaces/egraph/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [EGraphInvalidInputErrorCode](/reference/knotkit/e-graph/type-aliases/egraphinvalidinputerrorcode/)
* [EGraphErrorCode](/reference/knotkit/e-graph/type-aliases/egrapherrorcode/)
* [EGraphKind](/reference/knotkit/e-graph/type-aliases/egraphkind/)
## Variables
[Section titled “Variables”](#variables)
* [E_GRAPH_INVALID_INPUT_ERROR_CODES](/reference/knotkit/e-graph/variables/e_graph_invalid_input_error_codes/)
* [E_GRAPH_ERROR_CODES](/reference/knotkit/e-graph/variables/e_graph_error_codes/)
* [E_GRAPH_KINDS](/reference/knotkit/e-graph/variables/e_graph_kinds/)
* [\_\_E_GRAPH_LAYOUTS](/reference/knotkit/e-graph/variables/e_graph_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [eGraph](/reference/knotkit/e-graph/functions/egraph/)
# EGraphInvalidInputError
Defined in: [packages/e-graph/src/errors.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L8)
Thrown when a caller passes an argument or object that violates a public contract: an out-of-range value, a malformed id, or an object not produced by the package’s own factories.
Abstract so every concrete instance belongs to the throwing package’s own subclass, which fixes `Code` to that package’s error-code union and gives `.name` a package-specific value.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`EGraphInvalidInputErrorCode`](/reference/knotkit/e-graph/type-aliases/egraphinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new EGraphInvalidInputError**(`code`, `message`): `EGraphInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"FOREIGN_CLASS"` | `"INVALID_COST"` | `"COST_OVERFLOW"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`EGraphInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/e-graph"`
Defined in: [packages/e-graph/src/errors.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L9)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"FOREIGN_CLASS"` | `"INVALID_COST"` | `"COST_OVERFLOW"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
# eGraph
> **eGraph**<`Op`>(): [`EGraph`](/reference/knotkit/e-graph/interfaces/egraph/)<`Op`>
Defined in: [packages/e-graph/src/index.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L42)
Create an empty congruence relation over terms with string operators and ordered children.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Op
[Section titled “Op”](#op)
`Op` *extends* `string` = `string`
## Returns
[Section titled “Returns”](#returns)
[`EGraph`](/reference/knotkit/e-graph/interfaces/egraph/)<`Op`>
# EClass
Defined in: [packages/e-graph/src/index.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L11)
An opaque handle minted by one graph. Its identity survives class merges.
## Properties
[Section titled “Properties”](#properties)
### \[slot]
[Section titled “\[slot\]”](#slot)
> `readonly` **\[slot]**: `number`
Defined in: [packages/e-graph/src/index.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L12)
# EGraph
Defined in: [packages/e-graph/src/index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L18)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Op
[Section titled “Op”](#op)
`Op` *extends* `string`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hash-consed"`
Defined in: [packages/e-graph/src/index.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L19)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/e-graph/src/index.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L21)
Current number of equivalence classes.
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`operator`, `children?`) => [`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
Defined in: [packages/e-graph/src/index.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L25)
Intern an operator applied to its ordered children. One class lookup per child.
#### Parameters
[Section titled “Parameters”](#parameters)
##### operator
[Section titled “operator”](#operator)
`Op`
##### children?
[Section titled “children?”](#children)
readonly [`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)\[]
#### Returns
[Section titled “Returns”](#returns)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
#### Throws
[Section titled “Throws”](#throws)
FOREIGN_CLASS for a child from another graph.
***
### unite
[Section titled “unite”](#unite)
> `readonly` **unite**: (`left`, `right`) => `boolean`
Defined in: [packages/e-graph/src/index.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L29)
Merge two classes and propagate congruence to a fixed point. Returns whether the partition changed.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### left
[Section titled “left”](#left)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
##### right
[Section titled “right”](#right)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-1)
FOREIGN_CLASS for an unknown handle.
***
### equivalent
[Section titled “equivalent”](#equivalent)
> `readonly` **equivalent**: (`left`, `right`) => `boolean`
Defined in: [packages/e-graph/src/index.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L33)
Check equivalence under all equalities supplied so far.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### left
[Section titled “left”](#left-1)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
##### right
[Section titled “right”](#right-1)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
FOREIGN_CLASS for an unknown handle.
***
### extract
[Section titled “extract”](#extract)
> `readonly` **extract**: (`root`, `price`) => [`EGraphExpression`](/reference/knotkit/e-graph/interfaces/egraphexpression/)<`Op`>
Defined in: [packages/e-graph/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L38)
Extract a minimum-cost finite tree. Supply a pure, finite, nonnegative local price per operator.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### root
[Section titled “root”](#root)
[`EClass`](/reference/knotkit/e-graph/interfaces/eclass/)
##### price
[Section titled “price”](#price)
(`operator`) => `number`
#### Returns
[Section titled “Returns”](#returns-3)
[`EGraphExpression`](/reference/knotkit/e-graph/interfaces/egraphexpression/)<`Op`>
#### Throws
[Section titled “Throws”](#throws-3)
FOREIGN_CLASS for an unknown handle, INVALID_COST for an invalid price, or COST_OVERFLOW when all equivalent trees exceed the finite number range. Callback exceptions propagate.
# EGraphExpression
Defined in: [packages/e-graph/src/extract.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/extract.ts#L5)
A finite expression. Repeated children can share the same result object.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Op
[Section titled “Op”](#op)
`Op` *extends* `string`
## Properties
[Section titled “Properties”](#properties)
### operator
[Section titled “operator”](#operator)
> `readonly` **operator**: `Op`
Defined in: [packages/e-graph/src/extract.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/extract.ts#L6)
***
### children
[Section titled “children”](#children)
> `readonly` **children**: readonly `EGraphExpression`<`Op`>\[]
Defined in: [packages/e-graph/src/extract.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/extract.ts#L7)
***
### cost
[Section titled “cost”](#cost)
> `readonly` **cost**: `number`
Defined in: [packages/e-graph/src/extract.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/extract.ts#L9)
Local operator cost plus the cost of each child occurrence in order.
# EGraphErrorCode
> **EGraphErrorCode** = [`EGraphInvalidInputErrorCode`](/reference/knotkit/e-graph/type-aliases/egraphinvalidinputerrorcode/)
Defined in: [packages/e-graph/src/errors.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L5)
# EGraphInvalidInputErrorCode
> **EGraphInvalidInputErrorCode** = *typeof* [`E_GRAPH_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/e-graph/variables/e_graph_invalid_input_error_codes/)\[`number`]
Defined in: [packages/e-graph/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L4)
# EGraphKind
> **EGraphKind** = *typeof* [`E_GRAPH_KINDS`](/reference/knotkit/e-graph/variables/e_graph_kinds/)\[`number`]
Defined in: [packages/e-graph/src/index.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L16)
# E_GRAPH_ERROR_CODES
> `const` **E\_GRAPH_ERROR_CODES**: readonly [`EGraphErrorCode`](/reference/knotkit/e-graph/type-aliases/egrapherrorcode/)\[]
Defined in: [packages/e-graph/src/errors.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L6)
# E_GRAPH_INVALID_INPUT_ERROR_CODES
> `const` **E\_GRAPH_INVALID_INPUT_ERROR_CODES**: readonly \[`"FOREIGN_CLASS"`, `"INVALID_COST"`, `"COST_OVERFLOW"`]
Defined in: [packages/e-graph/src/errors.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/errors.ts#L3)
# E_GRAPH_KINDS
> `const` **E\_GRAPH_KINDS**: readonly \[`"hash-consed"`]
Defined in: [packages/e-graph/src/index.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L15)
# __E_GRAPH_LAYOUTS
> `const` **\_\_E_GRAPH_LAYOUTS**: `Readonly`<`Record`<[`EGraphKind`](/reference/knotkit/e-graph/type-aliases/egraphkind/), *typeof* [`eGraph`](/reference/knotkit/e-graph/functions/egraph/)>>
Defined in: [packages/e-graph/src/index.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/e-graph/src/index.ts#L127)
# knotkit/errors
## Classes
[Section titled “Classes”](#classes)
* [KnotkitError](/reference/knotkit/errors/classes/knotkiterror/)
* [InvalidInputError](/reference/knotkit/errors/classes/invalidinputerror/)
* [ParseError](/reference/knotkit/errors/classes/parseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [KnotkitErrorShape](/reference/knotkit/errors/interfaces/knotkiterrorshape/)
* [InvalidInputErrorShape](/reference/knotkit/errors/interfaces/invalidinputerrorshape/)
* [ParseErrorShape](/reference/knotkit/errors/interfaces/parseerrorshape/)
## Functions
[Section titled “Functions”](#functions)
* [isKnotkitError](/reference/knotkit/errors/functions/isknotkiterror/)
* [isInvalidInputError](/reference/knotkit/errors/functions/isinvalidinputerror/)
* [isParseError](/reference/knotkit/errors/functions/isparseerror/)
* [safeString](/reference/knotkit/errors/functions/safestring/)
* [assertElements](/reference/knotkit/errors/functions/assertelements/)
# InvalidInputError
Defined in: [packages/errors/src/index.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L37)
Thrown when a caller passes an argument or object that violates a public contract: an out-of-range value, a malformed id, or an object not produced by the package’s own factories.
Abstract so every concrete instance belongs to the throwing package’s own subclass, which fixes `Code` to that package’s error-code union and gives `.name` a package-specific value.
## Extends
[Section titled “Extends”](#extends)
* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`EGraphInvalidInputError`](/reference/knotkit/e-graph/classes/egraphinvalidinputerror/)
* [`BitsetInvalidInputError`](/reference/knotkit/bitset/classes/bitsetinvalidinputerror/)
* [`CacheInvalidInputError`](/reference/knotkit/cache/classes/cacheinvalidinputerror/)
* [`CasInvalidInputError`](/reference/knotkit/cas/classes/casinvalidinputerror/)
* [`CombinatoricsInvalidInputError`](/reference/knotkit/combinatorics/classes/combinatoricsinvalidinputerror/)
* [`DequeInvalidInputError`](/reference/knotkit/deque/classes/dequeinvalidinputerror/)
* [`DisjointSetInvalidInputError`](/reference/knotkit/disjoint-set/classes/disjointsetinvalidinputerror/)
* [`DistanceInvalidInputError`](/reference/knotkit/distance/classes/distanceinvalidinputerror/)
* [`DistributionInvalidInputError`](/reference/knotkit/distribution/classes/distributioninvalidinputerror/)
* [`EvolutionInvalidInputError`](/reference/knotkit/evolution/classes/evolutioninvalidinputerror/)
* [`FrequencyTableInvalidInputError`](/reference/knotkit/frequency-table/classes/frequencytableinvalidinputerror/)
* [`GraphInvalidInputError`](/reference/knotkit/graph/classes/graphinvalidinputerror/)
* [`HashInvalidInputError`](/reference/knotkit/hash/classes/hashinvalidinputerror/)
* [`HeapInvalidInputError`](/reference/knotkit/heap/classes/heapinvalidinputerror/)
* [`HypothesisTestInvalidInputError`](/reference/knotkit/hypothesis-test/classes/hypothesistestinvalidinputerror/)
* [`IntervalIndexInvalidInputError`](/reference/knotkit/interval-index/classes/intervalindexinvalidinputerror/)
* [`InvertedIndexInvalidInputError`](/reference/knotkit/inverted-index/classes/invertedindexinvalidinputerror/)
* [`KeyEncodingInvalidInputError`](/reference/knotkit/key-encoding/classes/keyencodinginvalidinputerror/)
* [`OrderedMapInvalidInputError`](/reference/knotkit/ordered-map/classes/orderedmapinvalidinputerror/)
* [`PrefixIndexInvalidInputError`](/reference/knotkit/prefix-index/classes/prefixindexinvalidinputerror/)
* [`PrngInvalidInputError`](/reference/knotkit/prng/classes/prnginvalidinputerror/)
* [`RateLimitInvalidInputError`](/reference/knotkit/rate-limit/classes/ratelimitinvalidinputerror/)
* [`SamplingInvalidInputError`](/reference/knotkit/sampling/classes/samplinginvalidinputerror/)
* [`ScalarSketchInvalidInputError`](/reference/knotkit/scalar-sketch/classes/scalarsketchinvalidinputerror/)
* [`SnapshotSetInvalidInputError`](/reference/knotkit/snapshot-set/classes/snapshotsetinvalidinputerror/)
* [`SortedBlockInvalidInputError`](/reference/knotkit/sorted-block/classes/sortedblockinvalidinputerror/)
* [`StaticFilterInvalidInputError`](/reference/knotkit/static-filter/classes/staticfilterinvalidinputerror/)
* [`TermIndexInvalidInputError`](/reference/knotkit/term-index/classes/termindexinvalidinputerror/)
* [`TrieInvalidInputError`](/reference/knotkit/trie/classes/trieinvalidinputerror/)
* [`WireInvalidInputError`](/reference/knotkit/wire/classes/wireinvalidinputerror/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Code
[Section titled “Code”](#code)
`Code` *extends* `string`
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new InvalidInputError**<`Code`>(`code`, `message`): `InvalidInputError`<`Code`>
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code-1)
`Code`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`InvalidInputError`<`Code`>
#### Overrides
[Section titled “Overrides”](#overrides)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`constructor`](/reference/knotkit/errors/classes/knotkiterror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `abstract` `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L18)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`moduleName`](/reference/knotkit/errors/classes/knotkiterror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`_tag`](/reference/knotkit/errors/classes/knotkiterror/#_tag)
***
### code
[Section titled “code”](#code-2)
> `readonly` **code**: `Code`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`code`](/reference/knotkit/errors/classes/knotkiterror/#code)
# KnotkitError
Defined in: [packages/errors/src/index.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L17)
Base class for every error thrown by a knotkit package.
`moduleName`, `_tag`, and `code` let callers inspect a failure without depending on a package-specific subclass identity. This matters when more than one copy of a package is loaded and concrete `instanceof` checks are unreliable.
## Extends
[Section titled “Extends”](#extends)
* `Error`
## Extended by
[Section titled “Extended by”](#extended-by)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new KnotkitError**(`message`): `KnotkitError`
Defined in: [packages/errors/src/index.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L22)
#### Parameters
[Section titled “Parameters”](#parameters)
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`KnotkitError`
#### Overrides
[Section titled “Overrides”](#overrides)
`Error.constructor`
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `abstract` `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L18)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `abstract` `readonly` **\_tag**: `string`
Defined in: [packages/errors/src/index.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L19)
***
### code
[Section titled “code”](#code)
> `abstract` `readonly` **code**: `string`
Defined in: [packages/errors/src/index.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L20)
# ParseError
Defined in: [packages/errors/src/index.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L54)
Thrown when decoding a serialized payload that is malformed, internally inconsistent, or fails element validation.
Abstract for the same reason as [InvalidInputError](/reference/knotkit/errors/classes/invalidinputerror/).
## Extends
[Section titled “Extends”](#extends)
* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BitsetParseError`](/reference/knotkit/bitset/classes/bitsetparseerror/)
* [`CasParseError`](/reference/knotkit/cas/classes/casparseerror/)
* [`DisjointSetParseError`](/reference/knotkit/disjoint-set/classes/disjointsetparseerror/)
* [`GraphParseError`](/reference/knotkit/graph/classes/graphparseerror/)
* [`HashParseError`](/reference/knotkit/hash/classes/hashparseerror/)
* [`HeapParseError`](/reference/knotkit/heap/classes/heapparseerror/)
* [`KeyEncodingParseError`](/reference/knotkit/key-encoding/classes/keyencodingparseerror/)
* [`ScalarSketchParseError`](/reference/knotkit/scalar-sketch/classes/scalarsketchparseerror/)
* [`SnapshotSetParseError`](/reference/knotkit/snapshot-set/classes/snapshotsetparseerror/)
* [`SortedBlockParseError`](/reference/knotkit/sorted-block/classes/sortedblockparseerror/)
* [`StaticFilterParseError`](/reference/knotkit/static-filter/classes/staticfilterparseerror/)
* [`TrieParseError`](/reference/knotkit/trie/classes/trieparseerror/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Code
[Section titled “Code”](#code)
`Code` *extends* `string`
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new ParseError**<`Code`>(`code`, `message`): `ParseError`<`Code`>
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code-1)
`Code`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`ParseError`<`Code`>
#### Overrides
[Section titled “Overrides”](#overrides)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`constructor`](/reference/knotkit/errors/classes/knotkiterror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `abstract` `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L18)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`moduleName`](/reference/knotkit/errors/classes/knotkiterror/#modulename)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`_tag`](/reference/knotkit/errors/classes/knotkiterror/#_tag)
***
### code
[Section titled “code”](#code-2)
> `readonly` **code**: `Code`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/).[`code`](/reference/knotkit/errors/classes/knotkiterror/#code)
# assertElements
> **assertElements**<`T`>(`values`, `isElement`, `makeError`): `asserts values is readonly T[]`
Defined in: [packages/errors/src/index.ts:144](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L144)
Assert that every element of `values` satisfies `isElement`, narrowing its type. Throws the error `makeError` builds for the first element that fails, naming its index.
Factored out because more than one package builds this same find-the-first-invalid-element check around its own [ParseError](/reference/knotkit/errors/classes/parseerror/) subclass when decoding a serialized payload’s element array.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `unknown`\[]
### isElement
[Section titled “isElement”](#iselement)
(`value`) => `value is T`
### makeError
[Section titled “makeError”](#makeerror)
(`invalidIndex`) => [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Returns
[Section titled “Returns”](#returns)
`asserts values is readonly T[]`
# isInvalidInputError
> **isInvalidInputError**(`value`): `value is InvalidInputErrorShape`
Defined in: [packages/errors/src/index.ts:113](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L113)
Whether `value` is a Knotkit error in the `InvalidInputError` category.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
`value is InvalidInputErrorShape`
# isKnotkitError
> **isKnotkitError**(`value`): `value is KnotkitErrorShape`
Defined in: [packages/errors/src/index.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L92)
Whether `value` carries the `moduleName`, `_tag`, `code`, and `message` fields every Knotkit error exposes. Structural, so it recognises an error from another realm or a duplicate bundle copy.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
`value is KnotkitErrorShape`
# isParseError
> **isParseError**(`value`): `value is ParseErrorShape`
Defined in: [packages/errors/src/index.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L118)
Whether `value` is a Knotkit error in the `ParseError` category.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
`value is ParseErrorShape`
# safeString
> **safeString**(`value`): `string`
Defined in: [packages/errors/src/index.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L127)
Format an unknown value for an error message without allowing its `toString` or `Symbol.toPrimitive` implementation to replace the caller’s intended error.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
`string`
# InvalidInputErrorShape
Defined in: [packages/errors/src/index.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L79)
A Knotkit error whose category is `InvalidInputError`.
## Extends
[Section titled “Extends”](#extends)
* [`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L72)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`moduleName`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#modulename)
***
### code
[Section titled “code”](#code)
> `readonly` **code**: `string`
Defined in: [packages/errors/src/index.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L74)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`code`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#code)
***
### message
[Section titled “message”](#message)
> `readonly` **message**: `string`
Defined in: [packages/errors/src/index.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L75)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`message`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#message)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L80)
#### Overrides
[Section titled “Overrides”](#overrides)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`_tag`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#_tag)
# KnotkitErrorShape
Defined in: [packages/errors/src/index.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L71)
Structural shape shared by every Knotkit error, independent of class identity.
Use it in a `catch` clause where the concrete class may come from another realm or a duplicate bundle copy, so `instanceof` would report a false negative.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`InvalidInputErrorShape`](/reference/knotkit/errors/interfaces/invalidinputerrorshape/)
* [`ParseErrorShape`](/reference/knotkit/errors/interfaces/parseerrorshape/)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L72)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `string`
Defined in: [packages/errors/src/index.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L73)
***
### code
[Section titled “code”](#code)
> `readonly` **code**: `string`
Defined in: [packages/errors/src/index.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L74)
***
### message
[Section titled “message”](#message)
> `readonly` **message**: `string`
Defined in: [packages/errors/src/index.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L75)
# ParseErrorShape
Defined in: [packages/errors/src/index.ts:84](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L84)
A Knotkit error whose category is `ParseError`.
## Extends
[Section titled “Extends”](#extends)
* [`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/)
## Properties
[Section titled “Properties”](#properties)
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `ModuleName`
Defined in: [packages/errors/src/index.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L72)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`moduleName`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#modulename)
***
### code
[Section titled “code”](#code)
> `readonly` **code**: `string`
Defined in: [packages/errors/src/index.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L74)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`code`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#code)
***
### message
[Section titled “message”](#message)
> `readonly` **message**: `string`
Defined in: [packages/errors/src/index.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L75)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`message`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#message)
***
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L85)
#### Overrides
[Section titled “Overrides”](#overrides)
[`KnotkitErrorShape`](/reference/knotkit/errors/interfaces/knotkiterrorshape/).[`_tag`](/reference/knotkit/errors/interfaces/knotkiterrorshape/#_tag)
# knotkit/evolution
## Classes
[Section titled “Classes”](#classes)
* [EvolutionInvalidInputError](/reference/knotkit/evolution/classes/evolutioninvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [EvaluatedCandidate](/reference/knotkit/evolution/interfaces/evaluatedcandidate/)
* [EvolutionSnapshot](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)
* [EvolutionContext](/reference/knotkit/evolution/interfaces/evolutioncontext/)
* [EvolutionOptions](/reference/knotkit/evolution/interfaces/evolutionoptions/)
* [Evolution](/reference/knotkit/evolution/interfaces/evolution/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [EvolutionInvalidInputErrorCode](/reference/knotkit/evolution/type-aliases/evolutioninvalidinputerrorcode/)
* [EvolutionErrorCode](/reference/knotkit/evolution/type-aliases/evolutionerrorcode/)
* [Objective](/reference/knotkit/evolution/type-aliases/objective/)
## Variables
[Section titled “Variables”](#variables)
* [EVOLUTION_INVALID_INPUT_ERROR_CODES](/reference/knotkit/evolution/variables/evolution_invalid_input_error_codes/)
* [EVOLUTION_ERROR_CODES](/reference/knotkit/evolution/variables/evolution_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [evolution](/reference/knotkit/evolution/functions/evolution/)
* [orderCrossover](/reference/knotkit/evolution/functions/ordercrossover/)
* [swapMutation](/reference/knotkit/evolution/functions/swapmutation/)
* [rotateLeftMutation](/reference/knotkit/evolution/functions/rotateleftmutation/)
* [rotateRightMutation](/reference/knotkit/evolution/functions/rotaterightmutation/)
* [inversionMutation](/reference/knotkit/evolution/functions/inversionmutation/)
* [tournamentSelection](/reference/knotkit/evolution/functions/tournamentselection/)
* [exponentialRankWeights](/reference/knotkit/evolution/functions/exponentialrankweights/)
* [exponentialRankLogWeights](/reference/knotkit/evolution/functions/exponentialranklogweights/)
* [rankSelection](/reference/knotkit/evolution/functions/rankselection/)
# EvolutionInvalidInputError
Defined in: [packages/evolution/src/errors.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L28)
Thrown when an evolution, selection, or permutation input violates its public contract.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`EvolutionInvalidInputErrorCode`](/reference/knotkit/evolution/type-aliases/evolutioninvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new EvolutionInvalidInputError**(`code`, `message`): `EvolutionInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_INDEX"` | `"DUPLICATE_ELEMENT"` | `"EMPTY_POPULATION"` | `"INVALID_GENERATION_COUNT"` | `"INVALID_SCORE"` | `"INVALID_SELECTION_SIZE"` | `"INVALID_TOURNAMENT_SIZE"` | `"INVALID_OBJECTIVE"` | `"INVALID_PERMUTATION"` | `"INVALID_CUT"` | `"UNEQUAL_PARENT_DOMAIN"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`EvolutionInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_INDEX"` | `"DUPLICATE_ELEMENT"` | `"EMPTY_POPULATION"` | `"INVALID_GENERATION_COUNT"` | `"INVALID_SCORE"` | `"INVALID_SELECTION_SIZE"` | `"INVALID_TOURNAMENT_SIZE"` | `"INVALID_OBJECTIVE"` | `"INVALID_PERMUTATION"` | `"INVALID_CUT"` | `"UNEQUAL_PARENT_DOMAIN"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/evolution"`
Defined in: [packages/evolution/src/errors.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L29)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# evolution
> **evolution**<`T`>(`options`): [`Evolution`](/reference/knotkit/evolution/interfaces/evolution/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:181](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L181)
Create a deterministic population evolution backed by closure state.
Construction copies the initial array and evaluates every candidate exactly once. Each `step()` calls `nextPopulation` exactly once and evaluates each returned candidate exactly once. Equal scores retain the first best candidate encountered, including across generations. Snapshot arrays and wrapper records are frozen, but arbitrary candidate values are not cloned or deep-frozen; callers and policies must treat them as immutable. Randomness is consumed only by the caller’s policy through the injected source. Callback exceptions pass through unchanged.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`EvolutionOptions`](/reference/knotkit/evolution/interfaces/evolutionoptions/)<`T`>
## Returns
[Section titled “Returns”](#returns)
[`Evolution`](/reference/knotkit/evolution/interfaces/evolution/)<`T`>
## Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` when the initial population is empty, `INVALID_OBJECTIVE` when the objective is unsupported, or `INVALID_SCORE` when evaluation returns a non-finite score.
# exponentialRankLogWeights
> **exponentialRankLogWeights**(`scores`, `objective`): readonly `number`\[]
Defined in: [packages/evolution/src/selection.ts:125](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/selection.ts#L125)
Return exponential competition-rank log-weights aligned to the source scores.
Rank zero is best and receives log-weight `-rank`, so a one-candidate population returns `[0]`. Ranking, ties, and validation match `exponentialRankWeights` exactly: `Math.exp` of every entry equals the matching weight. Every entry is finite at any rank, so no candidate becomes ineligible through underflow, and the entry for rank zero is `0` rather than `-0`. The input is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### scores
[Section titled “scores”](#scores)
readonly `number`\[]
### objective
[Section titled “objective”](#objective)
[`Objective`](/reference/knotkit/evolution/type-aliases/objective/)
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` for no scores, `INVALID_SCORE` for a non-finite score, or `INVALID_OBJECTIVE` for an unsupported objective.
# exponentialRankWeights
> **exponentialRankWeights**(`scores`, `objective`): readonly `number`\[]
Defined in: [packages/evolution/src/selection.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/selection.ts#L108)
Return exponential competition-rank weights aligned to the source scores.
Rank zero is best and receives weight `Math.exp(-rank)`, so a one-candidate population returns `[1]`. Equal scores share the rank of their first ordered position; the next distinct score’s rank includes every preceding candidate. Source index breaks sorting ties without changing tied weights. Very low-ranked weights may become zero only when `Math.exp(-rank)` underflows. The input is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### scores
[Section titled “scores”](#scores)
readonly `number`\[]
### objective
[Section titled “objective”](#objective)
[`Objective`](/reference/knotkit/evolution/type-aliases/objective/)
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` for no scores, `INVALID_SCORE` for a non-finite score, or `INVALID_OBJECTIVE` for an unsupported objective.
# inversionMutation
> **inversionMutation**<`T`>(`values`, `first`, `second`): readonly `T`\[]
Defined in: [packages/evolution/src/permutation.ts:113](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/permutation.ts#L113)
Reverse the inclusive segment between two indices in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `T`\[]
### first
[Section titled “first”](#first)
`number`
### second
[Section titled “second”](#second)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `T`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_PERMUTATION` when `values` is not an array or `INVALID_INDEX` when either index is not a safe integer inside it.
# orderCrossover
> **orderCrossover**<`T`>(`first`, `second`, `cut`): readonly \[readonly `T`\[], readonly `T`\[]]
Defined in: [packages/evolution/src/permutation.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/permutation.ts#L35)
Cross two permutations with an inclusive order-crossover cut.
Both parents must have equal length and contain the same unique values under `Set` SameValueZero equality. Each child keeps one parent’s cut segment and fills the other positions in the opposite parent’s cyclic order. Runs in O(n) expected time and O(n) auxiliary space, returns new readonly arrays, and never mutates either parent.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
readonly `T`\[]
### second
[Section titled “second”](#second)
readonly `T`\[]
### cut
[Section titled “cut”](#cut)
readonly \[`number`, `number`]
## Returns
[Section titled “Returns”](#returns)
readonly \[readonly `T`\[], readonly `T`\[]]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_PERMUTATION` when a parent is not an array, `DUPLICATE_ELEMENT` when either parent repeats a value, `UNEQUAL_PARENT_DOMAIN` when parent domains differ, or `INVALID_CUT` when the cut is not an ascending safe-integer pair inside both parents.
# rankSelection
> **rankSelection**(`random`, `scores`, `selectionSize`, `objective`): readonly `number`\[]
Defined in: [packages/evolution/src/selection.ts:143](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/selection.ts#L143)
Select source indices with replacement from exponential competition-rank weights.
Each result consumes one weighted-choice draw. Scores are validated and ranked once, remain unmodified, and the returned indices refer to the original score order.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### scores
[Section titled “scores”](#scores)
readonly `number`\[]
### selectionSize
[Section titled “selectionSize”](#selectionsize)
`number`
### objective
[Section titled “objective”](#objective)
[`Objective`](/reference/knotkit/evolution/type-aliases/objective/)
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` for no scores, `INVALID_SCORE` for a non-finite score, `INVALID_SELECTION_SIZE` for a negative or unsafe selection size, or `INVALID_OBJECTIVE` for an unsupported objective.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# rotateLeftMutation
> **rotateLeftMutation**<`T`>(`values`, `first`, `second`): readonly `T`\[]
Defined in: [packages/evolution/src/permutation.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/permutation.ts#L77)
Rotate an inclusive ascending segment one position left in a new array. Equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `T`\[]
### first
[Section titled “first”](#first)
`number`
### second
[Section titled “second”](#second)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `T`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_PERMUTATION` when `values` is not an array or `INVALID_INDEX` when an index is outside it or `first` exceeds `second`.
# rotateRightMutation
> **rotateRightMutation**<`T`>(`values`, `first`, `second`): readonly `T`\[]
Defined in: [packages/evolution/src/permutation.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/permutation.ts#L95)
Rotate an inclusive ascending segment one position right in a new array. Equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `T`\[]
### first
[Section titled “first”](#first)
`number`
### second
[Section titled “second”](#second)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `T`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_PERMUTATION` when `values` is not an array or `INVALID_INDEX` when an index is outside it or `first` exceeds `second`.
# swapMutation
> **swapMutation**<`T`>(`values`, `first`, `second`): readonly `T`\[]
Defined in: [packages/evolution/src/permutation.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/permutation.ts#L57)
Swap two indexed values in a new array. Index order is unrestricted and equal indices are a fresh-array no-op. Runs in O(n) time and space and never mutates the input.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `T`\[]
### first
[Section titled “first”](#first)
`number`
### second
[Section titled “second”](#second)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `T`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_PERMUTATION` when `values` is not an array or `INVALID_INDEX` when either index is not a safe integer inside it.
# tournamentSelection
> **tournamentSelection**(`random`, `scores`, `selectionSize`, `tournamentSize`, `objective`): readonly `number`\[]
Defined in: [packages/evolution/src/selection.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/selection.ts#L43)
Select source indices through independent tournaments.
Candidates are distinct inside one tournament, but the same source index may win multiple tournaments. Tied scores retain the first sampled index, which is the lowest source index because `sampleIndices` is canonical. Inputs are not mutated. The result is a new array and randomness is consumed separately for every tournament.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### scores
[Section titled “scores”](#scores)
readonly `number`\[]
### selectionSize
[Section titled “selectionSize”](#selectionsize)
`number`
### tournamentSize
[Section titled “tournamentSize”](#tournamentsize)
`number`
### objective
[Section titled “objective”](#objective)
[`Objective`](/reference/knotkit/evolution/type-aliases/objective/)
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` for no scores, `INVALID_SCORE` for a non-finite score, `INVALID_SELECTION_SIZE` for a negative or unsafe selection size, `INVALID_TOURNAMENT_SIZE` for a size outside `1..scores.length`, or `INVALID_OBJECTIVE` for an unsupported objective.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# EvaluatedCandidate
Defined in: [packages/evolution/src/evolution.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L13)
One candidate paired with the finite score returned by the configured evaluator.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### value
[Section titled “value”](#value)
> `readonly` **value**: `T`
Defined in: [packages/evolution/src/evolution.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L14)
***
### score
[Section titled “score”](#score)
> `readonly` **score**: `number`
Defined in: [packages/evolution/src/evolution.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L15)
# Evolution
Defined in: [packages/evolution/src/evolution.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L46)
A closure-backed evolution engine with no retained intermediate trace.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"evolution"`
Defined in: [packages/evolution/src/evolution.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L47)
## Methods
[Section titled “Methods”](#methods)
### snapshot()
[Section titled “snapshot()”](#snapshot)
> **snapshot**(): [`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L50)
Return the frozen current snapshot without evaluating, advancing, or consuming randomness.
#### Returns
[Section titled “Returns”](#returns)
[`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
***
### step()
[Section titled “step()”](#step)
> **step**(): [`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L58)
Produce and evaluate exactly one next population, then return its frozen snapshot.
#### Returns
[Section titled “Returns”](#returns-1)
[`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY_POPULATION` when the policy returns no candidates, or `INVALID_SCORE` when evaluation returns a non-finite score.
***
### run()
[Section titled “run()”](#run)
> **run**(`generations`): [`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L67)
Execute exactly `generations` steps without retaining intermediate snapshots.
#### Parameters
[Section titled “Parameters”](#parameters)
##### generations
[Section titled “generations”](#generations)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
[`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_GENERATION_COUNT` when the count is not a non-negative safe integer, `EMPTY_POPULATION` when a policy returns no candidates, or `INVALID_SCORE` when evaluation returns a non-finite score.
# EvolutionContext
Defined in: [packages/evolution/src/evolution.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L31)
The current immutable snapshot and caller-owned random source supplied to a population policy.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### snapshot
[Section titled “snapshot”](#snapshot)
> `readonly` **snapshot**: [`EvolutionSnapshot`](/reference/knotkit/evolution/interfaces/evolutionsnapshot/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L32)
***
### random
[Section titled “random”](#random)
> `readonly` **random**: [`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
Defined in: [packages/evolution/src/evolution.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L33)
# EvolutionOptions
Defined in: [packages/evolution/src/evolution.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L37)
Inputs required to construct a deterministic population evolution.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### initialPopulation
[Section titled “initialPopulation”](#initialpopulation)
> `readonly` **initialPopulation**: readonly `T`\[]
Defined in: [packages/evolution/src/evolution.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L38)
***
### evaluate
[Section titled “evaluate”](#evaluate)
> `readonly` **evaluate**: (`candidate`) => `number`
Defined in: [packages/evolution/src/evolution.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L39)
#### Parameters
[Section titled “Parameters”](#parameters)
##### candidate
[Section titled “candidate”](#candidate)
`T`
#### Returns
[Section titled “Returns”](#returns)
`number`
***
### objective
[Section titled “objective”](#objective)
> `readonly` **objective**: [`Objective`](/reference/knotkit/evolution/type-aliases/objective/)
Defined in: [packages/evolution/src/evolution.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L40)
***
### random
[Section titled “random”](#random)
> `readonly` **random**: [`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
Defined in: [packages/evolution/src/evolution.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L41)
***
### nextPopulation
[Section titled “nextPopulation”](#nextpopulation)
> `readonly` **nextPopulation**: (`context`) => readonly `T`\[]
Defined in: [packages/evolution/src/evolution.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L42)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### context
[Section titled “context”](#context)
[`EvolutionContext`](/reference/knotkit/evolution/interfaces/evolutioncontext/)<`T`>
#### Returns
[Section titled “Returns”](#returns-1)
readonly `T`\[]
# EvolutionSnapshot
Defined in: [packages/evolution/src/evolution.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L19)
The complete current state and bounded summary retained by an evolution engine.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"evolution-snapshot"`
Defined in: [packages/evolution/src/evolution.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L20)
***
### generation
[Section titled “generation”](#generation)
> `readonly` **generation**: `number`
Defined in: [packages/evolution/src/evolution.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L21)
***
### population
[Section titled “population”](#population)
> `readonly` **population**: readonly [`EvaluatedCandidate`](/reference/knotkit/evolution/interfaces/evaluatedcandidate/)<`T`>\[]
Defined in: [packages/evolution/src/evolution.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L22)
***
### generationBest
[Section titled “generationBest”](#generationbest)
> `readonly` **generationBest**: [`EvaluatedCandidate`](/reference/knotkit/evolution/interfaces/evaluatedcandidate/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L23)
***
### best
[Section titled “best”](#best)
> `readonly` **best**: [`EvaluatedCandidate`](/reference/knotkit/evolution/interfaces/evaluatedcandidate/)<`T`>
Defined in: [packages/evolution/src/evolution.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L24)
***
### meanScore
[Section titled “meanScore”](#meanscore)
> `readonly` **meanScore**: `number`
Defined in: [packages/evolution/src/evolution.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L25)
***
### worstScore
[Section titled “worstScore”](#worstscore)
> `readonly` **worstScore**: `number`
Defined in: [packages/evolution/src/evolution.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L26)
***
### generationsWithoutImprovement
[Section titled “generationsWithoutImprovement”](#generationswithoutimprovement)
> `readonly` **generationsWithoutImprovement**: `number`
Defined in: [packages/evolution/src/evolution.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/evolution.ts#L27)
# EvolutionErrorCode
> **EvolutionErrorCode** = [`EvolutionInvalidInputErrorCode`](/reference/knotkit/evolution/type-aliases/evolutioninvalidinputerrorcode/)
Defined in: [packages/evolution/src/errors.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L25)
A machine-readable error code emitted by `knotkit/evolution`.
# EvolutionInvalidInputErrorCode
> **EvolutionInvalidInputErrorCode** = *typeof* [`EVOLUTION_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/evolution/variables/evolution_invalid_input_error_codes/)\[`number`]
Defined in: [packages/evolution/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L22)
A machine-readable invalid-input code emitted by `knotkit/evolution`.
# Objective
> **Objective** = `"minimize"` | `"maximize"`
Defined in: [packages/evolution/src/objective.ts:2](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/objective.ts#L2)
The direction in which one finite numeric score improves on another.
# EVOLUTION_ERROR_CODES
> `const` **EVOLUTION_ERROR_CODES**: *typeof* [`EVOLUTION_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/evolution/variables/evolution_invalid_input_error_codes/) = `EVOLUTION_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/evolution/src/errors.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L19)
Every machine-readable error code emitted by `knotkit/evolution`.
# EVOLUTION_INVALID_INPUT_ERROR_CODES
> `const` **EVOLUTION_INVALID_INPUT_ERROR_CODES**: readonly \[`"EMPTY_POPULATION"`, `"INVALID_GENERATION_COUNT"`, `"INVALID_SCORE"`, `"INVALID_SELECTION_SIZE"`, `"INVALID_TOURNAMENT_SIZE"`, `"INVALID_OBJECTIVE"`, `"INVALID_PERMUTATION"`, `"INVALID_INDEX"`, `"INVALID_CUT"`, `"DUPLICATE_ELEMENT"`, `"UNEQUAL_PARENT_DOMAIN"`]
Defined in: [packages/evolution/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/evolution/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/evolution`.
# knotkit/frequency-table
## Classes
[Section titled “Classes”](#classes)
* [FrequencyTableInvalidInputError](/reference/knotkit/frequency-table/classes/frequencytableinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [FrequencyTable](/reference/knotkit/frequency-table/interfaces/frequencytable/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [FrequencyTableInvalidInputErrorCode](/reference/knotkit/frequency-table/type-aliases/frequencytableinvalidinputerrorcode/)
* [FrequencyTableErrorCode](/reference/knotkit/frequency-table/type-aliases/frequencytableerrorcode/)
* [FrequencyTableKind](/reference/knotkit/frequency-table/type-aliases/frequencytablekind/)
* [FrequencyTableFactory](/reference/knotkit/frequency-table/type-aliases/frequencytablefactory/)
## Variables
[Section titled “Variables”](#variables)
* [FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/frequency-table/variables/frequency_table_invalid_input_error_codes/)
* [FREQUENCY_TABLE_ERROR_CODES](/reference/knotkit/frequency-table/variables/frequency_table_error_codes/)
* [FREQUENCY_TABLE_KINDS](/reference/knotkit/frequency-table/variables/frequency_table_kinds/)
* [\_\_FREQUENCY_TABLE_LAYOUTS](/reference/knotkit/frequency-table/variables/frequency_table_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [fenwickFrequencyTable](/reference/knotkit/frequency-table/functions/fenwickfrequencytable/)
* [flatFrequencyTable](/reference/knotkit/frequency-table/functions/flatfrequencytable/)
# FrequencyTableInvalidInputError
Defined in: [packages/frequency-table/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L17)
A key, rank, range, or count update falls outside the frequency table’s domain.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`FrequencyTableInvalidInputErrorCode`](/reference/knotkit/frequency-table/type-aliases/frequencytableinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new FrequencyTableInvalidInputError**(`code`, `message`): `FrequencyTableInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_RANGE"` | `"INVALID_INDEX"` | `"INVALID_CAPACITY"` | `"INVALID_DELTA"` | `"COUNT_UNDERFLOW"` | `"COUNT_OVERFLOW"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`FrequencyTableInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_RANGE"` | `"INVALID_INDEX"` | `"INVALID_CAPACITY"` | `"INVALID_DELTA"` | `"COUNT_UNDERFLOW"` | `"COUNT_OVERFLOW"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/frequency-table"`
Defined in: [packages/frequency-table/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L18)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# fenwickFrequencyTable
> **fenwickFrequencyTable**(`capacity`): [`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
Defined in: [packages/frequency-table/src/fenwick-frequency-table.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/fenwick-frequency-table.ts#L63)
Create an empty binary indexed tree. Count, add, sum and selection take O(log(capacity + 1)). Construction and clearing take O(capacity + 1) and counters occupy 4(capacity + 1) bytes.
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
## Returns
[Section titled “Returns”](#returns)
[`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
## Throws
[Section titled “Throws”](#throws)
INVALID_CAPACITY unless capacity is an integer in \[0, 2^31 - 1].
# flatFrequencyTable
> **flatFrequencyTable**(`capacity`): [`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
Defined in: [packages/frequency-table/src/flat-frequency-table.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/flat-frequency-table.ts#L43)
Create an empty flat histogram using four bytes per key. Count and add take O(1). Sums scan the requested range. Selection, initialization, and clearing take O(capacity) in the worst case.
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
## Returns
[Section titled “Returns”](#returns)
[`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
## Throws
[Section titled “Throws”](#throws)
INVALID_CAPACITY unless capacity is an integer in \[0, 2^31 - 1].
# FrequencyTable
Defined in: [packages/frequency-table/src/frequency-table.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L5)
Exact nonnegative frequencies over integer keys in \[0, capacity).
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"flat"` | `"fenwick"`
Defined in: [packages/frequency-table/src/frequency-table.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L6)
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L8)
Number of addressable keys, fixed at construction.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L10)
Sum of all frequencies, including repeated occurrences. O(1).
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`key`, `delta?`) => `void`
Defined in: [packages/frequency-table/src/frequency-table.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L16)
Add delta occurrences of key, defaulting to one. Negative deltas remove occurrences.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`number`
##### delta?
[Section titled “delta?”](#delta)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
INVALID_INDEX for an invalid key, INVALID_DELTA for a delta that is not a safe integer, COUNT_UNDERFLOW for a negative resulting frequency, or COUNT_OVERFLOW for a total above 2^32 - 1. A rejected update leaves all counts unchanged.
***
### count
[Section titled “count”](#count)
> `readonly` **count**: (`key`) => `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L20)
Read the exact frequency of key. An unobserved key has count zero.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
INVALID_INDEX for a key outside the integer domain.
***
### prefixSum
[Section titled “prefixSum”](#prefixsum)
> `readonly` **prefixSum**: (`end`) => `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L24)
Sum frequencies of keys in \[0, end).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### end
[Section titled “end”](#end)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
INVALID_RANGE for a noninteger endpoint or one outside \[0, capacity].
***
### rangeSum
[Section titled “rangeSum”](#rangesum)
> `readonly` **rangeSum**: (`start`, `end`) => `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L28)
Sum frequencies of keys in \[start, end).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### start
[Section titled “start”](#start)
`number`
##### end
[Section titled “end”](#end-1)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
INVALID_RANGE for noninteger, reversed, or out-of-domain bounds.
***
### at
[Section titled “at”](#at)
> `readonly` **at**: (`position`) => `number`
Defined in: [packages/frequency-table/src/frequency-table.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L32)
Read the key at a zero-based position, counting duplicates. Negative positions count from the end.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### position
[Section titled “position”](#position)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
#### Throws
[Section titled “Throws”](#throws-4)
INVALID_INDEX for a noninteger position or one outside \[-size, size).
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/frequency-table/src/frequency-table.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L34)
Reset all counts, retaining the allocated storage. O(capacity).
#### Returns
[Section titled “Returns”](#returns-5)
`void`
# FrequencyTableErrorCode
> **FrequencyTableErrorCode** = [`FrequencyTableInvalidInputErrorCode`](/reference/knotkit/frequency-table/type-aliases/frequencytableinvalidinputerrorcode/)
Defined in: [packages/frequency-table/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L14)
# FrequencyTableFactory
> **FrequencyTableFactory** = (`capacity`) => [`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
Defined in: [packages/frequency-table/src/frequency-table.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L37)
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
## Returns
[Section titled “Returns”](#returns)
[`FrequencyTable`](/reference/knotkit/frequency-table/interfaces/frequencytable/)
# FrequencyTableInvalidInputErrorCode
> **FrequencyTableInvalidInputErrorCode** = *typeof* [`FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/frequency-table/variables/frequency_table_invalid_input_error_codes/)\[`number`]
Defined in: [packages/frequency-table/src/errors.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L13)
# FrequencyTableKind
> **FrequencyTableKind** = *typeof* [`FREQUENCY_TABLE_KINDS`](/reference/knotkit/frequency-table/variables/frequency_table_kinds/)\[`number`]
Defined in: [packages/frequency-table/src/frequency-table.ts:2](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L2)
# FREQUENCY_TABLE_ERROR_CODES
> `const` **FREQUENCY_TABLE_ERROR_CODES**: *typeof* [`FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/frequency-table/variables/frequency_table_invalid_input_error_codes/) = `FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/frequency-table/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L11)
# FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES
> `const` **FREQUENCY_TABLE_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_CAPACITY"`, `"INVALID_INDEX"`, `"INVALID_RANGE"`, `"INVALID_DELTA"`, `"COUNT_UNDERFLOW"`, `"COUNT_OVERFLOW"`]
Defined in: [packages/frequency-table/src/errors.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/errors.ts#L3)
# FREQUENCY_TABLE_KINDS
> `const` **FREQUENCY_TABLE_KINDS**: readonly \[`"fenwick"`, `"flat"`]
Defined in: [packages/frequency-table/src/frequency-table.ts:1](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/frequency-table.ts#L1)
# __FREQUENCY_TABLE_LAYOUTS
> `const` **\_\_FREQUENCY_TABLE_LAYOUTS**: `Readonly`<`Record`<[`FrequencyTableKind`](/reference/knotkit/frequency-table/type-aliases/frequencytablekind/), [`FrequencyTableFactory`](/reference/knotkit/frequency-table/type-aliases/frequencytablefactory/)>>
Defined in: [packages/frequency-table/src/layouts.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/frequency-table/src/layouts.ts#L6)
Every layout, keyed by the kind its factory reports.
# knotkit/graph
## Classes
[Section titled “Classes”](#classes)
* [GraphInvalidInputError](/reference/knotkit/graph/classes/graphinvalidinputerror/)
* [GraphParseError](/reference/knotkit/graph/classes/graphparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [BreadthFirstSearchOptions](/reference/knotkit/graph/interfaces/breadthfirstsearchoptions/)
* [BreadthFirstSearchResult](/reference/knotkit/graph/interfaces/breadthfirstsearchresult/)
* [ConnectedComponentsResult](/reference/knotkit/graph/interfaces/connectedcomponentsresult/)
* [DijkstraOptions](/reference/knotkit/graph/interfaces/dijkstraoptions/)
* [DijkstraResult](/reference/knotkit/graph/interfaces/dijkstraresult/)
* [Adjacency](/reference/knotkit/graph/interfaces/adjacency/)
* [GraphEdges](/reference/knotkit/graph/interfaces/graphedges/)
* [GraphOptions](/reference/knotkit/graph/interfaces/graphoptions/)
* [CompressedSparseRowGraph](/reference/knotkit/graph/interfaces/compressedsparserowgraph/)
* [AdjacencyMatrixGraph](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/)
* [MutableGraph](/reference/knotkit/graph/interfaces/mutablegraph/)
* [GridAdjacencyOptions](/reference/knotkit/graph/interfaces/gridadjacencyoptions/)
* [GridAdjacency](/reference/knotkit/graph/interfaces/gridadjacency/)
* [PathSource](/reference/knotkit/graph/interfaces/pathsource/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [DijkstraStep](/reference/knotkit/graph/type-aliases/dijkstrastep/)
* [GraphInvalidInputErrorCode](/reference/knotkit/graph/type-aliases/graphinvalidinputerrorcode/)
* [GraphParseErrorCode](/reference/knotkit/graph/type-aliases/graphparseerrorcode/)
* [GraphErrorCode](/reference/knotkit/graph/type-aliases/grapherrorcode/)
* [FloydWarshallResult](/reference/knotkit/graph/type-aliases/floydwarshallresult/)
* [GraphKind](/reference/knotkit/graph/type-aliases/graphkind/)
* [GraphEdgeTuple](/reference/knotkit/graph/type-aliases/graphedgetuple/)
* [Graph](/reference/knotkit/graph/type-aliases/graph/)
* [GraphFactory](/reference/knotkit/graph/type-aliases/graphfactory/)
* [TopologicalOrderResult](/reference/knotkit/graph/type-aliases/topologicalorderresult/)
## Variables
[Section titled “Variables”](#variables)
* [GRAPH_INVALID_INPUT_ERROR_CODES](/reference/knotkit/graph/variables/graph_invalid_input_error_codes/)
* [GRAPH_PARSE_ERROR_CODES](/reference/knotkit/graph/variables/graph_parse_error_codes/)
* [GRAPH_ERROR_CODES](/reference/knotkit/graph/variables/graph_error_codes/)
* [GRAPH_KINDS](/reference/knotkit/graph/variables/graph_kinds/)
* [GRAPH_MAX_VERTEX_COUNT](/reference/knotkit/graph/variables/graph_max_vertex_count/)
* [GRAPH_MAX_MATRIX_BYTES](/reference/knotkit/graph/variables/graph_max_matrix_bytes/)
* [\_\_GRAPH_LAYOUTS](/reference/knotkit/graph/variables/graph_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [adjacencyListGraph](/reference/knotkit/graph/functions/adjacencylistgraph/)
* [adjacencyMatrixGraph](/reference/knotkit/graph/functions/adjacencymatrixgraph/)
* [breadthFirstSearch](/reference/knotkit/graph/functions/breadthfirstsearch/)
* [compressedSparseRowGraph](/reference/knotkit/graph/functions/compressedsparserowgraph/)
* [connectedComponents](/reference/knotkit/graph/functions/connectedcomponents/)
* [dijkstra](/reference/knotkit/graph/functions/dijkstra/)
* [floydWarshall](/reference/knotkit/graph/functions/floydwarshall/)
* [gridAdjacency](/reference/knotkit/graph/functions/gridadjacency/)
* [path](/reference/knotkit/graph/functions/path/)
* [topologicalOrder](/reference/knotkit/graph/functions/topologicalorder/)
# GraphInvalidInputError
Defined in: [packages/graph/src/errors.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L65)
Thrown when a caller passes a vertex outside the graph, an edge or weight the graph’s flags forbid, an algorithm a graph of the wrong direction, a grid with bad dimensions, or an object the package did not produce where only its own graph will do.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`GraphInvalidInputErrorCode`](/reference/knotkit/graph/type-aliases/graphinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new GraphInvalidInputError**(`code`, `message`): `GraphInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"INVALID_WEIGHT"` | `"INVALID_VERTEX_COUNT"` | `"INVALID_VERTEX"` | `"INVALID_EDGE"` | `"MISSING_WEIGHT"` | `"UNEXPECTED_WEIGHT"` | `"INVALID_FLAG"` | `"SELF_LOOP"` | `"PARALLEL_EDGE"` | `"PARALLEL_EDGES_UNSUPPORTED"` | `"NEGATIVE_WEIGHT"` | `"DIRECTED_GRAPH_REQUIRED"` | `"UNDIRECTED_GRAPH_REQUIRED"` | `"INVALID_GRID"` | `"FOREIGN_GRAPH"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`GraphInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"MAX_CAPACITY_EXCEEDED"` | `"MODIFIED_DURING_ITERATION"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"INVALID_WEIGHT"` | `"INVALID_VERTEX_COUNT"` | `"INVALID_VERTEX"` | `"INVALID_EDGE"` | `"MISSING_WEIGHT"` | `"UNEXPECTED_WEIGHT"` | `"INVALID_FLAG"` | `"SELF_LOOP"` | `"PARALLEL_EDGE"` | `"PARALLEL_EDGES_UNSUPPORTED"` | `"NEGATIVE_WEIGHT"` | `"DIRECTED_GRAPH_REQUIRED"` | `"UNDIRECTED_GRAPH_REQUIRED"` | `"INVALID_GRID"` | `"FOREIGN_GRAPH"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/graph"`
Defined in: [packages/graph/src/errors.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L66)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# GraphParseError
Defined in: [packages/graph/src/errors.ts:70](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L70)
Thrown when decoding a `serializeGraph` artifact that is malformed or internally inconsistent.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`GraphParseErrorCode`](/reference/knotkit/graph/type-aliases/graphparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new GraphParseError**(`code`, `message`): `GraphParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_EDGE_SEQUENCE"` | `"INVALID_GRAPH_FLAGS"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`GraphParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_EDGE_SEQUENCE"` | `"INVALID_GRAPH_FLAGS"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/graph"`
Defined in: [packages/graph/src/errors.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L71)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# adjacencyListGraph
> **adjacencyListGraph**(`options`): [`MutableGraph`](/reference/knotkit/graph/interfaces/mutablegraph/)
Defined in: [packages/graph/src/adjacency-list-graph.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/adjacency-list-graph.ts#L50)
A mutable graph stored as one sorted row per vertex, each row a slot with spare capacity in one shared `Int32Array` of neighbor ids, plus a parallel `Float64Array` of weights when the graph is weighted.
It is the one layout that grows after construction, through `addVertex`, `addEdge`, and `deleteEdge`. A row that outgrows its slot moves to the end of the shared array with doubled capacity, and the array is compacted once dead slots and spare capacity outweigh the stored arcs, so a graph that shrinks gives its memory back. An isolated vertex costs 12 bytes. A directed graph also keeps a reverse row per vertex for predecessor queries, which doubles its memory.
`addEdge` keeps the row sorted, which costs `O(log d + d)` for a vertex of degree `d`. Building from `options.edges` is `O(n + m)`, so a large edge set known up front belongs in `options.edges` rather than in a loop of `addEdge` calls.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`GraphOptions`](/reference/knotkit/graph/interfaces/graphoptions/)
The vertex count, the two required flags, the multigraph flags, and the edges.
## Returns
[Section titled “Returns”](#returns)
[`MutableGraph`](/reference/knotkit/graph/interfaces/mutablegraph/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX_COUNT`, `INVALID_FLAG`, `INVALID_EDGE`, `INVALID_VERTEX`, `MISSING_WEIGHT`, `UNEXPECTED_WEIGHT`, `INVALID_WEIGHT`, `SELF_LOOP`, or `PARALLEL_EDGE` when an option or an edge breaks the contract, or `MAX_CAPACITY_EXCEEDED` when storage cannot be allocated.
## Example
[Section titled “Example”](#example)
```ts
const graph = adjacencyListGraph({ vertexCount: 2, directed: false, weighted: true })
const city = graph.addVertex() // 2
graph.addEdge(0, city, 7)
graph.hasEdge(city, 0) // true
```
# adjacencyMatrixGraph
> **adjacencyMatrixGraph**(`options`): [`AdjacencyMatrixGraph`](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/)
Defined in: [packages/graph/src/adjacency-matrix-graph.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/adjacency-matrix-graph.ts#L40)
An immutable graph stored as a dense `n × n` matrix: one bit per vertex pair when unweighted, or one `Float64Array` cell per pair when weighted, with `Infinity` for “no edge”.
`hasEdge` is `O(1)`, and an unweighted dense graph costs `n² / 8` bytes whatever its edge count. A row walk costs `O(n / 32 + d)` unweighted and `O(n)` weighted, so on a sparse graph every traversal pays for the absent edges. Storage is checked against `GRAPH_MAX_MATRIX_BYTES` before it is allocated. One cell per pair means the matrix cannot hold parallel edges.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`GraphOptions`](/reference/knotkit/graph/interfaces/graphoptions/)
The vertex count, the two required flags, `selfLoops`, and the edges.
## Returns
[Section titled “Returns”](#returns)
[`AdjacencyMatrixGraph`](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/)
## Throws
[Section titled “Throws”](#throws)
With code `PARALLEL_EDGES_UNSUPPORTED` for `parallelEdges: true`; `MAX_CAPACITY_EXCEEDED` when the matrix would pass `GRAPH_MAX_MATRIX_BYTES` or the runtime refuses it; or `INVALID_VERTEX_COUNT`, `INVALID_FLAG`, `INVALID_EDGE`, `INVALID_VERTEX`, `MISSING_WEIGHT`, `UNEXPECTED_WEIGHT`, `INVALID_WEIGHT`, `SELF_LOOP`, or `PARALLEL_EDGE` when an option or an edge breaks the contract.
## Example
[Section titled “Example”](#example)
```ts
const graph = adjacencyMatrixGraph({ vertexCount: 3, directed: true, weighted: true, edges: [[0, 2, 4]] })
graph.hasEdge(0, 2) // true
```
# breadthFirstSearch
> **breadthFirstSearch**(`adjacency`, `options`): [`BreadthFirstSearchResult`](/reference/knotkit/graph/interfaces/breadthfirstsearchresult/)
Defined in: [packages/graph/src/breadth-first-search.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L46)
Find the fewest-hops distance from the nearest of `sources` to every vertex. `O(n)` extra memory, and `O(n)` time plus one row walk per reached vertex: `O(n + m)` on `compressed-sparse-row` and `adjacency-list`, but `O(n² / 32 + m)` on an unweighted `adjacency-matrix` and `O(n²)` on a weighted one, whose rows cost `O(n / 32 + d)` and `O(n)` whatever their degree.
Several sources make it a multi-source search, which is the “rotting oranges” and “walls and gates” shape. Neighbors are visited in ascending id, so the parents are the same on every layout.
## Parameters
[Section titled “Parameters”](#parameters)
### adjacency
[Section titled “adjacency”](#adjacency)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)
### options
[Section titled “options”](#options)
[`BreadthFirstSearchOptions`](/reference/knotkit/graph/interfaces/breadthfirstsearchoptions/)
## Returns
[Section titled “Returns”](#returns)
[`BreadthFirstSearchResult`](/reference/knotkit/graph/interfaces/breadthfirstsearchresult/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when a source, the target, or a reported neighbor is outside the graph; `INVALID_WEIGHT` when a hand-written `adjacency` reports a weight that is not a finite number; `INVALID_VERTEX_COUNT` or `INVALID_FLAG` when it misstates its shape; or `MODIFIED_DURING_ITERATION` when iterating `sources` changed the adjacency list being searched.
## Example
[Section titled “Example”](#example)
```ts
const { distance } = breadthFirstSearch(graph, { sources: [0] })
distance[3] // hops from vertex 0 to vertex 3, or -1
```
# compressedSparseRowGraph
> **compressedSparseRowGraph**(`options`): [`CompressedSparseRowGraph`](/reference/knotkit/graph/interfaces/compressedsparserowgraph/)
Defined in: [packages/graph/src/compressed-sparse-row-graph.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/compressed-sparse-row-graph.ts#L35)
An immutable graph stored as compressed sparse rows: one `Int32Array` of row offsets and one flat array of neighbor ids, plus a flat `Float64Array` of weights when the graph is weighted.
It is the layout for an edge set known up front: `4(n + 1) + 4m'` bytes, plus `8m'` when weighted, where `m'` is the stored arcs (`2m` undirected). Rows are contiguous, so a walk reads memory in order. A directed graph counts its in-degrees into one `Int32Array` on the first `inDegree` call, and builds its transposed rows only on the first `forEachPredecessor` call, keeping them and dropping the counts.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`GraphOptions`](/reference/knotkit/graph/interfaces/graphoptions/)
The vertex count, the two required flags, the multigraph flags, and the edges.
## Returns
[Section titled “Returns”](#returns)
[`CompressedSparseRowGraph`](/reference/knotkit/graph/interfaces/compressedsparserowgraph/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX_COUNT`, `INVALID_FLAG`, `INVALID_EDGE`, `INVALID_VERTEX`, `MISSING_WEIGHT`, `UNEXPECTED_WEIGHT`, `INVALID_WEIGHT`, `SELF_LOOP`, or `PARALLEL_EDGE` when an option or an edge breaks the contract, or `MAX_CAPACITY_EXCEEDED` when storage cannot be allocated.
## Example
[Section titled “Example”](#example)
```ts
const graph = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: [[0, 1], [0, 2], [1, 3], [2, 3]],
})
graph.neighbors(0) // Int32Array [1, 2]
```
# connectedComponents
> **connectedComponents**(`adjacency`): [`ConnectedComponentsResult`](/reference/knotkit/graph/interfaces/connectedcomponentsresult/)
Defined in: [packages/graph/src/connected-components.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/connected-components.ts#L33)
Label the connected components of an undirected graph. `O(n + m)` on `compressed-sparse-row` and `adjacency-list`; it walks every row once, so an `adjacency-matrix` costs `O(n² / 32 + m)` unweighted and `O(n²)` weighted.
Labels are assigned by breadth-first search from each unlabelled vertex in ascending id, so vertex `0` is always in component `0` and the labels are the same on every layout.
## Parameters
[Section titled “Parameters”](#parameters)
### adjacency
[Section titled “adjacency”](#adjacency)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)
## Returns
[Section titled “Returns”](#returns)
[`ConnectedComponentsResult`](/reference/knotkit/graph/interfaces/connectedcomponentsresult/)
## Throws
[Section titled “Throws”](#throws)
With code `UNDIRECTED_GRAPH_REQUIRED` for a directed graph, whose weak and strong components are different questions; or, from a hand-written `adjacency`, `INVALID_VERTEX` or `INVALID_WEIGHT` for a neighbor or weight it reports, and `INVALID_VERTEX_COUNT` or `INVALID_FLAG` when it misstates its shape.
## Example
[Section titled “Example”](#example)
```ts
const { count, component } = connectedComponents(graph)
component[3] === component[7] // whether 3 and 7 are connected
```
# dijkstra
> **dijkstra**(`adjacency`, `options`): [`DijkstraResult`](/reference/knotkit/graph/interfaces/dijkstraresult/)
Defined in: [packages/graph/src/dijkstra.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L92)
Find the cheapest total cost from the nearest of `sources` to every vertex, with Dijkstra’s algorithm over `knotkit/heap`’s indexed priority queue. With `target` or a nonempty `targets` iterable, only settled vertices hold a distance and parent. An unreachable target leaves the search to exhaust the frontier. `targets` takes linear time to read and stores each distinct target once. The search uses `O(n)` extra memory and `O((n + m) log n)` time plus one row walk per expanded vertex, which is within that bound on `compressed-sparse-row` and `adjacency-list` and adds `O(n² / 32)` on an unweighted `adjacency-matrix` and `O(n²)` on a weighted one.
Named for the algorithm because it carries a precondition the caller must check: every cost is non-negative. Every edge out of an expanded vertex is priced and checked, including one into a vertex already settled, so a stored negative weight or a negative `cost` fails when the search first walks that edge rather than yielding a wrong distance.
Distances are float64 sums, subject to rounding. A sum that overflows to `Infinity` reads as unreached, as an explicitly infinite `cost` does.
## Parameters
[Section titled “Parameters”](#parameters)
### adjacency
[Section titled “adjacency”](#adjacency)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)
### options
[Section titled “options”](#options)
[`DijkstraOptions`](/reference/knotkit/graph/interfaces/dijkstraoptions/)
## Returns
[Section titled “Returns”](#returns)
[`DijkstraResult`](/reference/knotkit/graph/interfaces/dijkstraresult/)
## Throws
[Section titled “Throws”](#throws)
With code `NEGATIVE_WEIGHT` for a negative cost, `INVALID_WEIGHT` for a cost that is not a number or is `NaN` or a hand-written `adjacency` weight that is not a finite number, `INVALID_VERTEX` when a source, a target, or a reported neighbor is outside the graph, `INVALID_VERTEX_COUNT` or `INVALID_FLAG` when a hand-written `adjacency` misstates its shape, or `MODIFIED_DURING_ITERATION` when a `cost` callback changes the adjacency list being searched.
## Example
[Section titled “Example”](#example)
```ts
const result = dijkstra(graph, { sources: [0], target: 4 })
result.distance[4] // cheapest cost from 0 to 4, or Infinity
path(result, 4) // Int32Array [0, …, 4]
```
# floydWarshall
> **floydWarshall**(`graph`): [`FloydWarshallResult`](/reference/knotkit/graph/type-aliases/floydwarshallresult/)
Defined in: [packages/graph/src/floyd-warshall.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/floyd-warshall.ts#L50)
Compute the shortest distance between every pair of vertices with the Floyd-Warshall algorithm. `O(n³ + R)` time and `8n²` bytes, where `R` is the cost of enumerating every row once: `O(n + m)` on `compressed-sparse-row` and `adjacency-list`, parallel copies included, and `O(n²)` on `adjacency-matrix`.
Named for the algorithm because its cost is the caller’s to check. It runs on any layout and allocates its own distance matrix, so an all-pairs question does not decide the storage. Negative weights are allowed. On an undirected graph a negative edge is itself a negative cycle, since it can be walked back and forth. Parallel edges contribute their smallest weight, and an unweighted edge weighs `1`. When some cycle is negative, a Bellman-Ford pass over the rows, `O(n · R)` more, finds a vertex on that cycle.
Distances are float64 sums. They are exact while the absolute weights along every path sum to at most `Number.MAX_VALUE`; a partial sum past it rounds to `Infinity`, which reads as unreachable.
## Parameters
[Section titled “Parameters”](#parameters)
### graph
[Section titled “graph”](#graph)
[`Graph`](/reference/knotkit/graph/type-aliases/graph/)
## Returns
[Section titled “Returns”](#returns)
[`FloydWarshallResult`](/reference/knotkit/graph/type-aliases/floydwarshallresult/)
## Throws
[Section titled “Throws”](#throws)
With code `MAX_CAPACITY_EXCEEDED` when `8n²` bytes would pass `GRAPH_MAX_MATRIX_BYTES` or the runtime refuses the allocation.
## Example
[Section titled “Example”](#example)
```ts
const result = floydWarshall(graph)
if (!result.negativeCycle) result.distance[from * graph.vertexCount + to]
```
# gridAdjacency
> **gridAdjacency**(`options`): [`GridAdjacency`](/reference/knotkit/graph/interfaces/gridadjacency/)
Defined in: [packages/graph/src/grid-adjacency.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L74)
Treat a board of cells as a graph without storing it: each cell is a vertex, and each move to a neighboring cell is an edge of weight `1`.
Every algorithm that takes an `Adjacency` accepts the result, which is all but `floydWarshall`: the fewest moves through a maze is one `breadthFirstSearch`, and the islands are `connectedComponents`. A closed cell is still a vertex, an isolated one with a component of its own, so count islands as the distinct labels of the open cells, as in the example. Moves are visited in ascending cell order. Memory is `O(1)`; a walk over one cell is `O(1)` plus the callbacks.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`GridAdjacencyOptions`](/reference/knotkit/graph/interfaces/gridadjacencyoptions/)
## Returns
[Section titled “Returns”](#returns)
[`GridAdjacency`](/reference/knotkit/graph/interfaces/gridadjacency/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_GRID` when `rows` or `columns` is not a positive integer, when the board would hold more than `GRAPH_MAX_VERTEX_COUNT` cells, or when `connectivity` is not `4` or `8`.
## Example
[Section titled “Example”](#example)
```ts
const grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]
const open = (cell: number) => grid[Math.floor(cell / 3)][cell % 3] === 1
const board = gridAdjacency({ rows: 3, columns: 3, open })
board.cell(1, 1) // 4
const { component } = connectedComponents(board)
const islands = new Set()
for (let cell = 0; cell < board.vertexCount; cell += 1) if (open(cell)) islands.add(component[cell])
islands.size // 3; connectedComponents(board).count is 7, one per water cell as well
```
# path
> **path**(`result`, `target`): `Int32Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/graph/src/path.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/path.ts#L22)
The vertices of the path a search found from a source to `target`, source first, or `undefined` when the search never reached `target`. `O(path length)`.
## Parameters
[Section titled “Parameters”](#parameters)
### result
[Section titled “result”](#result)
[`PathSource`](/reference/knotkit/graph/interfaces/pathsource/)
### target
[Section titled “target”](#target)
`number`
## Returns
[Section titled “Returns”](#returns)
`Int32Array`<`ArrayBufferLike`> | `undefined`
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `target` is outside the result.
## Example
[Section titled “Example”](#example)
```ts
path(breadthFirstSearch(graph, { sources: [0] }), 5) // Int32Array [0, 2, 5]
```
# topologicalOrder
> **topologicalOrder**(`adjacency`): [`TopologicalOrderResult`](/reference/knotkit/graph/type-aliases/topologicalorderresult/)
Defined in: [packages/graph/src/topological-order.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/topological-order.ts#L43)
Order the vertices so every edge points forward, or return one directed cycle that makes that impossible. `O(n + m)` on `compressed-sparse-row` and `adjacency-list`; it walks every row twice, so an `adjacency-matrix` costs `O(n² / 32 + m)` unweighted and `O(n²)` weighted.
Kahn’s algorithm, starting from the vertices with no predecessor in ascending id and taking them first in, first out, so the order is the same on every layout. A cycle is an answer, not a failure: the result says which one it holds. A self-loop is a cycle of one vertex.
## Parameters
[Section titled “Parameters”](#parameters)
### adjacency
[Section titled “adjacency”](#adjacency)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)
## Returns
[Section titled “Returns”](#returns)
[`TopologicalOrderResult`](/reference/knotkit/graph/type-aliases/topologicalorderresult/)
## Throws
[Section titled “Throws”](#throws)
With code `DIRECTED_GRAPH_REQUIRED` for an undirected graph, where every edge would be a cycle of two vertices; or, from a hand-written `adjacency`, `INVALID_VERTEX` or `INVALID_WEIGHT` for a neighbor or weight it reports, and `INVALID_VERTEX_COUNT` or `INVALID_FLAG` when it misstates its shape.
## Example
[Section titled “Example”](#example)
```ts
const result = topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
else report(result.cycle)
```
# Adjacency
Defined in: [packages/graph/src/graph.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L47)
The smallest record every algorithm reads: how many vertices there are, whether edges have a direction, and a walk over one vertex’s neighbors.
Every [Graph](/reference/knotkit/graph/type-aliases/graph/) is one, `gridAdjacency` returns one, and a caller can write one by hand for a graph it never stores, such as the words one letter apart from a given word.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`GridAdjacency`](/reference/knotkit/graph/interfaces/gridadjacency/)
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L49)
Vertices are the integers `0 … vertexCount - 1`.
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L51)
Whether an edge from `u` to `v` leaves `v` without a way back to `u`.
***
### forEachNeighbor
[Section titled “forEachNeighbor”](#foreachneighbor)
> `readonly` **forEachNeighbor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L61)
Call `visit(neighbor, weight)` once per stored edge out of `vertex`, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight `1`. A hand-written adjacency reports a finite number: an algorithm reading it throws `INVALID_VERTEX` for a neighbor outside the graph and `INVALID_WEIGHT` for any other weight.
#### Parameters
[Section titled “Parameters”](#parameters)
##### vertex
[Section titled “vertex”](#vertex)
`number`
##### visit
[Section titled “visit”](#visit)
(`neighbor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `vertex` is not in `0 … vertexCount - 1`.
# AdjacencyMatrixGraph
Defined in: [packages/graph/src/graph.ts:168](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L168)
The `adjacency-matrix` layout: an immutable dense matrix, what `adjacencyMatrixGraph` returns.
## Extends
[Section titled “Extends”](#extends)
* `GraphSurface`
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L49)
Vertices are the integers `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`GraphSurface.vertexCount`
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L51)
Whether an edge from `u` to `v` leaves `v` without a way back to `u`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`GraphSurface.directed`
***
### forEachNeighbor
[Section titled “forEachNeighbor”](#foreachneighbor)
> `readonly` **forEachNeighbor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L61)
Call `visit(neighbor, weight)` once per stored edge out of `vertex`, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight `1`. A hand-written adjacency reports a finite number: an algorithm reading it throws `INVALID_VERTEX` for a neighbor outside the graph and `INVALID_WEIGHT` for any other weight.
#### Parameters
[Section titled “Parameters”](#parameters)
##### vertex
[Section titled “vertex”](#vertex)
`number`
##### visit
[Section titled “visit”](#visit)
(`neighbor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `vertex` is not in `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`GraphSurface.forEachNeighbor`
***
### weighted
[Section titled “weighted”](#weighted)
> `readonly` **weighted**: `boolean`
Defined in: [packages/graph/src/graph.ts:115](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L115)
Whether every edge stores a weight.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`GraphSurface.weighted`
***
### parallelEdges
[Section titled “parallelEdges”](#paralleledges)
> `readonly` **parallelEdges**: `boolean`
Defined in: [packages/graph/src/graph.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L117)
Whether repeated edges between the same endpoints are kept as separate copies.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`GraphSurface.parallelEdges`
***
### selfLoops
[Section titled “selfLoops”](#selfloops)
> `readonly` **selfLoops**: `boolean`
Defined in: [packages/graph/src/graph.ts:119](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L119)
Whether an edge may join a vertex to itself.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
`GraphSurface.selfLoops`
***
### edgeCount
[Section titled “edgeCount”](#edgecount)
> `readonly` **edgeCount**: `number`
Defined in: [packages/graph/src/graph.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L121)
Number of stored edges, each undirected edge and each self-loop counted once.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`GraphSurface.edgeCount`
***
### hasEdge
[Section titled “hasEdge”](#hasedge)
> `readonly` **hasEdge**: (`from`, `to`) => `boolean`
Defined in: [packages/graph/src/graph.ts:126](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L126)
Whether an edge runs from `from` to `to`. Total: returns `false` for an endpoint outside the graph instead of throwing.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### from
[Section titled “from”](#from)
`number`
##### to
[Section titled “to”](#to)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`GraphSurface.hasEdge`
***
### outDegree
[Section titled “outDegree”](#outdegree)
> `readonly` **outDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L133)
How many stored edges leave `vertex`, parallel copies included and a self-loop counted once.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### vertex
[Section titled “vertex”](#vertex-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`GraphSurface.outDegree`
***
### inDegree
[Section titled “inDegree”](#indegree)
> `readonly` **inDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:139](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L139)
How many stored edges enter `vertex`. Equal to [outDegree](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/#outdegree) on an undirected graph.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### vertex
[Section titled “vertex”](#vertex-2)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`GraphSurface.inDegree`
***
### forEachPredecessor
[Section titled “forEachPredecessor”](#foreachpredecessor)
> `readonly` **forEachPredecessor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L147)
Call `visit(predecessor, weight)` once per stored edge into `vertex`, in ascending predecessor id. On an undirected graph this walks the same row as [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor).
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### vertex
[Section titled “vertex”](#vertex-3)
`number`
##### visit
[Section titled “visit”](#visit-1)
(`predecessor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`GraphSurface.forEachPredecessor`
***
### neighbors
[Section titled “neighbors”](#neighbors)
> `readonly` **neighbors**: (`vertex`) => `Int32Array`
Defined in: [packages/graph/src/graph.ts:154](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L154)
The neighbors of `vertex` as a fresh `Int32Array`, in the order [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor) visits them. Writing to it never changes the graph.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### vertex
[Section titled “vertex”](#vertex-4)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`Int32Array`
#### Throws
[Section titled “Throws”](#throws-4)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`GraphSurface.neighbors`
***
### edges
[Section titled “edges”](#edges)
> `readonly` **edges**: () => [`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
Defined in: [packages/graph/src/graph.ts:159](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L159)
Every edge as fresh columns, ordered by source and then by row order. An undirected edge appears once, with `source <= target`.
#### Returns
[Section titled “Returns”](#returns-6)
[`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`GraphSurface.edges`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"adjacency-matrix"`
Defined in: [packages/graph/src/graph.ts:169](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L169)
The storage layout: `'adjacency-list'`, `'compressed-sparse-row'`, or `'adjacency-matrix'`.
#### Overrides
[Section titled “Overrides”](#overrides)
`GraphSurface.kind`
# BreadthFirstSearchOptions
Defined in: [packages/graph/src/breadth-first-search.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L6)
Where a breadth-first search starts, and the vertex at which it may stop early.
## Properties
[Section titled “Properties”](#properties)
### sources
[Section titled “sources”](#sources)
> `readonly` **sources**: `Iterable`<`number`>
Defined in: [packages/graph/src/breadth-first-search.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L8)
Start vertices, all at distance `0`. A repeated source is ignored after its first appearance.
***
### target?
[Section titled “target?”](#target)
> `readonly` `optional` **target?**: `number`
Defined in: [packages/graph/src/breadth-first-search.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L10)
Stop as soon as this vertex is reached. Vertices not yet reached then read as unreached.
# BreadthFirstSearchResult
Defined in: [packages/graph/src/breadth-first-search.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L14)
A breadth-first search’s answer, as arrays indexed by vertex.
## Properties
[Section titled “Properties”](#properties)
### distance
[Section titled “distance”](#distance)
> `readonly` **distance**: `Int32Array`
Defined in: [packages/graph/src/breadth-first-search.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L16)
Hops from the nearest source, or `-1` when unreached.
***
### parent
[Section titled “parent”](#parent)
> `readonly` **parent**: `Int32Array`
Defined in: [packages/graph/src/breadth-first-search.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L18)
The vertex each one was reached from, or `-1` for a source and for an unreached vertex.
***
### visitOrder
[Section titled “visitOrder”](#visitorder)
> `readonly` **visitOrder**: `Int32Array`
Defined in: [packages/graph/src/breadth-first-search.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L20)
Every reached vertex, in the order the search reached it.
# CompressedSparseRowGraph
Defined in: [packages/graph/src/graph.ts:163](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L163)
The `compressed-sparse-row` layout: immutable packed rows, what `compressedSparseRowGraph` returns.
## Extends
[Section titled “Extends”](#extends)
* `GraphSurface`
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L49)
Vertices are the integers `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`GraphSurface.vertexCount`
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L51)
Whether an edge from `u` to `v` leaves `v` without a way back to `u`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`GraphSurface.directed`
***
### forEachNeighbor
[Section titled “forEachNeighbor”](#foreachneighbor)
> `readonly` **forEachNeighbor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L61)
Call `visit(neighbor, weight)` once per stored edge out of `vertex`, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight `1`. A hand-written adjacency reports a finite number: an algorithm reading it throws `INVALID_VERTEX` for a neighbor outside the graph and `INVALID_WEIGHT` for any other weight.
#### Parameters
[Section titled “Parameters”](#parameters)
##### vertex
[Section titled “vertex”](#vertex)
`number`
##### visit
[Section titled “visit”](#visit)
(`neighbor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `vertex` is not in `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`GraphSurface.forEachNeighbor`
***
### weighted
[Section titled “weighted”](#weighted)
> `readonly` **weighted**: `boolean`
Defined in: [packages/graph/src/graph.ts:115](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L115)
Whether every edge stores a weight.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`GraphSurface.weighted`
***
### parallelEdges
[Section titled “parallelEdges”](#paralleledges)
> `readonly` **parallelEdges**: `boolean`
Defined in: [packages/graph/src/graph.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L117)
Whether repeated edges between the same endpoints are kept as separate copies.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`GraphSurface.parallelEdges`
***
### selfLoops
[Section titled “selfLoops”](#selfloops)
> `readonly` **selfLoops**: `boolean`
Defined in: [packages/graph/src/graph.ts:119](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L119)
Whether an edge may join a vertex to itself.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
`GraphSurface.selfLoops`
***
### edgeCount
[Section titled “edgeCount”](#edgecount)
> `readonly` **edgeCount**: `number`
Defined in: [packages/graph/src/graph.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L121)
Number of stored edges, each undirected edge and each self-loop counted once.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`GraphSurface.edgeCount`
***
### hasEdge
[Section titled “hasEdge”](#hasedge)
> `readonly` **hasEdge**: (`from`, `to`) => `boolean`
Defined in: [packages/graph/src/graph.ts:126](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L126)
Whether an edge runs from `from` to `to`. Total: returns `false` for an endpoint outside the graph instead of throwing.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### from
[Section titled “from”](#from)
`number`
##### to
[Section titled “to”](#to)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`GraphSurface.hasEdge`
***
### outDegree
[Section titled “outDegree”](#outdegree)
> `readonly` **outDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L133)
How many stored edges leave `vertex`, parallel copies included and a self-loop counted once.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### vertex
[Section titled “vertex”](#vertex-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`GraphSurface.outDegree`
***
### inDegree
[Section titled “inDegree”](#indegree)
> `readonly` **inDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:139](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L139)
How many stored edges enter `vertex`. Equal to [outDegree](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/#outdegree) on an undirected graph.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### vertex
[Section titled “vertex”](#vertex-2)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`GraphSurface.inDegree`
***
### forEachPredecessor
[Section titled “forEachPredecessor”](#foreachpredecessor)
> `readonly` **forEachPredecessor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L147)
Call `visit(predecessor, weight)` once per stored edge into `vertex`, in ascending predecessor id. On an undirected graph this walks the same row as [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor).
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### vertex
[Section titled “vertex”](#vertex-3)
`number`
##### visit
[Section titled “visit”](#visit-1)
(`predecessor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`GraphSurface.forEachPredecessor`
***
### neighbors
[Section titled “neighbors”](#neighbors)
> `readonly` **neighbors**: (`vertex`) => `Int32Array`
Defined in: [packages/graph/src/graph.ts:154](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L154)
The neighbors of `vertex` as a fresh `Int32Array`, in the order [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor) visits them. Writing to it never changes the graph.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### vertex
[Section titled “vertex”](#vertex-4)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`Int32Array`
#### Throws
[Section titled “Throws”](#throws-4)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`GraphSurface.neighbors`
***
### edges
[Section titled “edges”](#edges)
> `readonly` **edges**: () => [`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
Defined in: [packages/graph/src/graph.ts:159](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L159)
Every edge as fresh columns, ordered by source and then by row order. An undirected edge appears once, with `source <= target`.
#### Returns
[Section titled “Returns”](#returns-6)
[`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`GraphSurface.edges`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"compressed-sparse-row"`
Defined in: [packages/graph/src/graph.ts:164](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L164)
The storage layout: `'adjacency-list'`, `'compressed-sparse-row'`, or `'adjacency-matrix'`.
#### Overrides
[Section titled “Overrides”](#overrides)
`GraphSurface.kind`
# ConnectedComponentsResult
Defined in: [packages/graph/src/connected-components.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/connected-components.ts#L6)
Which component each vertex belongs to, and how many components there are.
## Properties
[Section titled “Properties”](#properties)
### count
[Section titled “count”](#count)
> `readonly` **count**: `number`
Defined in: [packages/graph/src/connected-components.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/connected-components.ts#L8)
Number of components; an isolated vertex is a component of its own.
***
### component
[Section titled “component”](#component)
> `readonly` **component**: `Int32Array`
Defined in: [packages/graph/src/connected-components.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/connected-components.ts#L10)
The component label of each vertex, in `0 … count - 1`, numbered in order of each component’s smallest vertex.
# DijkstraOptions
Defined in: [packages/graph/src/dijkstra.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L28)
Where a shortest-path search starts, where it may stop, and what an edge costs.
## Properties
[Section titled “Properties”](#properties)
### sources
[Section titled “sources”](#sources)
> `readonly` **sources**: `Iterable`<`number`>
Defined in: [packages/graph/src/dijkstra.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L30)
Start vertices, all at distance `0`.
***
### target?
[Section titled “target?”](#target)
> `readonly` `optional` **target?**: `number`
Defined in: [packages/graph/src/dijkstra.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L32)
One requested destination. When `targets` is also set, the search waits for all requested destinations.
***
### targets?
[Section titled “targets?”](#targets)
> `readonly` `optional` **targets?**: `Iterable`<`number`, `any`, `any`>
Defined in: [packages/graph/src/dijkstra.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L34)
Stop once all these vertices and `target`, if supplied, settle. Duplicates are ignored.
***
### cost?
[Section titled “cost?”](#cost)
> `readonly` `optional` **cost?**: (`from`, `to`, `weight`) => `number`
Defined in: [packages/graph/src/dijkstra.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L42)
The cost of walking one edge, in place of its stored weight. Called with the edge’s endpoints and stored weight (`1` when unweighted), once for every edge out of each expanded vertex. The last requested target settles without expansion. The callback must return a non-negative number and leave the graph unchanged. `Infinity` skips the edge.
#### Parameters
[Section titled “Parameters”](#parameters)
##### from
[Section titled “from”](#from)
`number`
##### to
[Section titled “to”](#to)
`number`
##### weight
[Section titled “weight”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
`number`
***
### trace?
[Section titled “trace?”](#trace)
> `readonly` `optional` **trace?**: [`DijkstraStep`](/reference/knotkit/graph/type-aliases/dijkstrastep/)\[]
Defined in: [packages/graph/src/dijkstra.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L48)
Receives a [DijkstraStep](/reference/knotkit/graph/type-aliases/dijkstrastep/) for each settle and relaxation, in order, so a caller can replay the search. Omitted, the search allocates no step objects. A relaxation’s `weight` is the cost the search used, after `cost`.
# DijkstraResult
Defined in: [packages/graph/src/dijkstra.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L52)
A shortest-path search’s answer, as arrays indexed by vertex.
## Properties
[Section titled “Properties”](#properties)
### distance
[Section titled “distance”](#distance)
> `readonly` **distance**: `Float64Array`
Defined in: [packages/graph/src/dijkstra.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L54)
The least total cost from the nearest source, or `Infinity` when unreached.
***
### parent
[Section titled “parent”](#parent)
> `readonly` **parent**: `Int32Array`
Defined in: [packages/graph/src/dijkstra.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L56)
The vertex each one was reached from on a cheapest path, or `-1` for a source and for an unreached vertex.
# GraphEdges
Defined in: [packages/graph/src/graph.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L72)
Every edge of a graph as three parallel columns: edge `i` runs from `sources[i]` to `targets[i]` with weight `weights[i]`.
`weights` is present exactly when the graph is weighted. The same record is accepted back as `GraphOptions.edges`, so converting between layouts never builds a tuple.
## Properties
[Section titled “Properties”](#properties)
### sources
[Section titled “sources”](#sources)
> `readonly` **sources**: `Int32Array`
Defined in: [packages/graph/src/graph.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L73)
***
### targets
[Section titled “targets”](#targets)
> `readonly` **targets**: `Int32Array`
Defined in: [packages/graph/src/graph.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L74)
***
### weights
[Section titled “weights”](#weights)
> `readonly` **weights**: `Float64Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/graph/src/graph.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L75)
# GraphOptions
Defined in: [packages/graph/src/graph.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L85)
The options every graph factory accepts, whatever its layout, so `__GRAPH_LAYOUTS[kind](options)` constructs any of them.
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:87](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L87)
Vertices are the integers `0 … vertexCount - 1`. For 1-based input, pass `n + 1` and leave vertex `0` isolated.
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L89)
Required: guessing it wrong changes every answer.
***
### weighted
[Section titled “weighted”](#weighted)
> `readonly` **weighted**: `boolean`
Defined in: [packages/graph/src/graph.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L91)
Required: a weighted graph needs a weight on every edge, and an unweighted graph rejects one.
***
### parallelEdges?
[Section titled “parallelEdges?”](#paralleledges)
> `readonly` `optional` **parallelEdges?**: `boolean`
Defined in: [packages/graph/src/graph.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L93)
Keep every copy of a repeated edge. Defaults to `false`, where a repeated edge with the same weight is a no-op.
***
### selfLoops?
[Section titled “selfLoops?”](#selfloops)
> `readonly` `optional` **selfLoops?**: `boolean`
Defined in: [packages/graph/src/graph.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L95)
Allow an edge from a vertex to itself. Defaults to `false`.
***
### edges?
[Section titled “edges?”](#edges)
> `readonly` `optional` **edges?**: [`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/) | `Iterable`<[`GraphEdgeTuple`](/reference/knotkit/graph/type-aliases/graphedgetuple/), `any`, `any`>
Defined in: [packages/graph/src/graph.ts:101](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L101)
Edges to add, in order, as `[from, to]` or `[from, to, weight]` tuples or as the columns a graph’s `edges()` returns. On an undirected graph `[u, v]` and `[v, u]` are the same edge.
# GridAdjacency
Defined in: [packages/graph/src/grid-adjacency.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L29)
An [Adjacency](/reference/knotkit/graph/interfaces/adjacency/) over a `rows × columns` board, where cell `(row, column)` is vertex `row * columns + column`.
## Extends
[Section titled “Extends”](#extends)
* [`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L49)
Vertices are the integers `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/).[`vertexCount`](/reference/knotkit/graph/interfaces/adjacency/#vertexcount)
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L51)
Whether an edge from `u` to `v` leaves `v` without a way back to `u`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/).[`directed`](/reference/knotkit/graph/interfaces/adjacency/#directed)
***
### forEachNeighbor
[Section titled “forEachNeighbor”](#foreachneighbor)
> `readonly` **forEachNeighbor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L61)
Call `visit(neighbor, weight)` once per stored edge out of `vertex`, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight `1`. A hand-written adjacency reports a finite number: an algorithm reading it throws `INVALID_VERTEX` for a neighbor outside the graph and `INVALID_WEIGHT` for any other weight.
#### Parameters
[Section titled “Parameters”](#parameters)
##### vertex
[Section titled “vertex”](#vertex)
`number`
##### visit
[Section titled “visit”](#visit)
(`neighbor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `vertex` is not in `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/).[`forEachNeighbor`](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor)
***
### rows
[Section titled “rows”](#rows)
> `readonly` **rows**: `number`
Defined in: [packages/graph/src/grid-adjacency.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L30)
***
### columns
[Section titled “columns”](#columns)
> `readonly` **columns**: `number`
Defined in: [packages/graph/src/grid-adjacency.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L31)
***
### cell
[Section titled “cell”](#cell)
> `readonly` **cell**: (`row`, `column`) => `number`
Defined in: [packages/graph/src/grid-adjacency.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L37)
The vertex of the cell at `(row, column)`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### row
[Section titled “row”](#row)
`number`
##### column
[Section titled “column”](#column)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_VERTEX` when the position is off the board.
# GridAdjacencyOptions
Defined in: [packages/graph/src/grid-adjacency.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L12)
The board a [gridAdjacency](/reference/knotkit/graph/functions/gridadjacency/) walks, and which moves it allows.
## Properties
[Section titled “Properties”](#properties)
### rows
[Section titled “rows”](#rows)
> `readonly` **rows**: `number`
Defined in: [packages/graph/src/grid-adjacency.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L14)
Number of rows, a positive integer.
***
### columns
[Section titled “columns”](#columns)
> `readonly` **columns**: `number`
Defined in: [packages/graph/src/grid-adjacency.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L16)
Number of columns, a positive integer.
***
### connectivity?
[Section titled “connectivity?”](#connectivity)
> `readonly` `optional` **connectivity?**: `4` | `8`
Defined in: [packages/graph/src/grid-adjacency.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L18)
`4` for orthogonal moves (the default), `8` to add the diagonals.
***
### open?
[Section titled “open?”](#open)
> `readonly` `optional` **open?**: (`cell`) => `boolean`
Defined in: [packages/graph/src/grid-adjacency.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L20)
Whether a cell can be entered or left at all. A closed cell has no edges, and the grid stays undirected.
#### Parameters
[Section titled “Parameters”](#parameters)
##### cell
[Section titled “cell”](#cell)
`number`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
***
### passable?
[Section titled “passable?”](#passable)
> `readonly` `optional` **passable?**: (`from`, `to`) => `boolean`
Defined in: [packages/graph/src/grid-adjacency.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/grid-adjacency.ts#L25)
Whether the single move from `from` to `to` is allowed. Setting it makes the grid directed, because a move allowed one way may be refused the other.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### from
[Section titled “from”](#from)
`number`
##### to
[Section titled “to”](#to)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
# MutableGraph
Defined in: [packages/graph/src/graph.ts:177](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L177)
A [Graph](/reference/knotkit/graph/type-aliases/graph/) that grows: the `adjacency-list` layout, what `adjacencyListGraph` returns. No other layout has these members, so calling a mutator on an immutable graph is a type error.
## Extends
[Section titled “Extends”](#extends)
* `GraphSurface`
## Properties
[Section titled “Properties”](#properties)
### vertexCount
[Section titled “vertexCount”](#vertexcount)
> `readonly` **vertexCount**: `number`
Defined in: [packages/graph/src/graph.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L49)
Vertices are the integers `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`GraphSurface.vertexCount`
***
### directed
[Section titled “directed”](#directed)
> `readonly` **directed**: `boolean`
Defined in: [packages/graph/src/graph.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L51)
Whether an edge from `u` to `v` leaves `v` without a way back to `u`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`GraphSurface.directed`
***
### forEachNeighbor
[Section titled “forEachNeighbor”](#foreachneighbor)
> `readonly` **forEachNeighbor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L61)
Call `visit(neighbor, weight)` once per stored edge out of `vertex`, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight `1`. A hand-written adjacency reports a finite number: an algorithm reading it throws `INVALID_VERTEX` for a neighbor outside the graph and `INVALID_WEIGHT` for any other weight.
#### Parameters
[Section titled “Parameters”](#parameters)
##### vertex
[Section titled “vertex”](#vertex)
`number`
##### visit
[Section titled “visit”](#visit)
(`neighbor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_VERTEX` when `vertex` is not in `0 … vertexCount - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`GraphSurface.forEachNeighbor`
***
### weighted
[Section titled “weighted”](#weighted)
> `readonly` **weighted**: `boolean`
Defined in: [packages/graph/src/graph.ts:115](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L115)
Whether every edge stores a weight.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`GraphSurface.weighted`
***
### parallelEdges
[Section titled “parallelEdges”](#paralleledges)
> `readonly` **parallelEdges**: `boolean`
Defined in: [packages/graph/src/graph.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L117)
Whether repeated edges between the same endpoints are kept as separate copies.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`GraphSurface.parallelEdges`
***
### selfLoops
[Section titled “selfLoops”](#selfloops)
> `readonly` **selfLoops**: `boolean`
Defined in: [packages/graph/src/graph.ts:119](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L119)
Whether an edge may join a vertex to itself.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
`GraphSurface.selfLoops`
***
### edgeCount
[Section titled “edgeCount”](#edgecount)
> `readonly` **edgeCount**: `number`
Defined in: [packages/graph/src/graph.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L121)
Number of stored edges, each undirected edge and each self-loop counted once.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`GraphSurface.edgeCount`
***
### hasEdge
[Section titled “hasEdge”](#hasedge)
> `readonly` **hasEdge**: (`from`, `to`) => `boolean`
Defined in: [packages/graph/src/graph.ts:126](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L126)
Whether an edge runs from `from` to `to`. Total: returns `false` for an endpoint outside the graph instead of throwing.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### from
[Section titled “from”](#from)
`number`
##### to
[Section titled “to”](#to)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`GraphSurface.hasEdge`
***
### outDegree
[Section titled “outDegree”](#outdegree)
> `readonly` **outDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L133)
How many stored edges leave `vertex`, parallel copies included and a self-loop counted once.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### vertex
[Section titled “vertex”](#vertex-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`GraphSurface.outDegree`
***
### inDegree
[Section titled “inDegree”](#indegree)
> `readonly` **inDegree**: (`vertex`) => `number`
Defined in: [packages/graph/src/graph.ts:139](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L139)
How many stored edges enter `vertex`. Equal to [outDegree](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/#outdegree) on an undirected graph.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### vertex
[Section titled “vertex”](#vertex-2)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`GraphSurface.inDegree`
***
### forEachPredecessor
[Section titled “forEachPredecessor”](#foreachpredecessor)
> `readonly` **forEachPredecessor**: (`vertex`, `visit`) => `void`
Defined in: [packages/graph/src/graph.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L147)
Call `visit(predecessor, weight)` once per stored edge into `vertex`, in ascending predecessor id. On an undirected graph this walks the same row as [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor).
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### vertex
[Section titled “vertex”](#vertex-3)
`number`
##### visit
[Section titled “visit”](#visit-1)
(`predecessor`, `weight`) => `void`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`GraphSurface.forEachPredecessor`
***
### neighbors
[Section titled “neighbors”](#neighbors)
> `readonly` **neighbors**: (`vertex`) => `Int32Array`
Defined in: [packages/graph/src/graph.ts:154](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L154)
The neighbors of `vertex` as a fresh `Int32Array`, in the order [forEachNeighbor](/reference/knotkit/graph/interfaces/adjacency/#foreachneighbor) visits them. Writing to it never changes the graph.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### vertex
[Section titled “vertex”](#vertex-4)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`Int32Array`
#### Throws
[Section titled “Throws”](#throws-4)
With code `INVALID_VERTEX` when `vertex` is outside the graph.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`GraphSurface.neighbors`
***
### edges
[Section titled “edges”](#edges)
> `readonly` **edges**: () => [`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
Defined in: [packages/graph/src/graph.ts:159](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L159)
Every edge as fresh columns, ordered by source and then by row order. An undirected edge appears once, with `source <= target`.
#### Returns
[Section titled “Returns”](#returns-6)
[`GraphEdges`](/reference/knotkit/graph/interfaces/graphedges/)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`GraphSurface.edges`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"adjacency-list"`
Defined in: [packages/graph/src/graph.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L178)
The storage layout: `'adjacency-list'`, `'compressed-sparse-row'`, or `'adjacency-matrix'`.
#### Overrides
[Section titled “Overrides”](#overrides)
`GraphSurface.kind`
***
### addVertex
[Section titled “addVertex”](#addvertex)
> `readonly` **addVertex**: () => `number`
Defined in: [packages/graph/src/graph.ts:185](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L185)
Add an isolated vertex. `O(1)` amortized.
#### Returns
[Section titled “Returns”](#returns-7)
`number`
The new vertex, which is the old `vertexCount`.
#### Throws
[Section titled “Throws”](#throws-5)
With code `MAX_CAPACITY_EXCEEDED` past `GRAPH_MAX_VERTEX_COUNT`.
***
### addEdge
[Section titled “addEdge”](#addedge)
> `readonly` **addEdge**: (`from`, `to`, `weight?`) => `boolean`
Defined in: [packages/graph/src/graph.ts:195](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L195)
Add an edge. `O(log d + d)`, where `d` is the endpoint’s degree, because the row stays sorted.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### from
[Section titled “from”](#from-1)
`number`
##### to
[Section titled “to”](#to-1)
`number`
##### weight?
[Section titled “weight?”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns-8)
`boolean`
`true` when an edge was added; `false` when the graph is simple and already holds the same edge with the same weight.
#### Throws
[Section titled “Throws”](#throws-6)
With code `INVALID_VERTEX`, `MISSING_WEIGHT`, `UNEXPECTED_WEIGHT`, `INVALID_WEIGHT`, `SELF_LOOP`, or `PARALLEL_EDGE`.
***
### deleteEdge
[Section titled “deleteEdge”](#deleteedge)
> `readonly` **deleteEdge**: (`from`, `to`) => `boolean`
Defined in: [packages/graph/src/graph.ts:202](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L202)
Delete every copy of the edge from `from` to `to`.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### from
[Section titled “from”](#from-2)
`number`
##### to
[Section titled “to”](#to-2)
`number`
#### Returns
[Section titled “Returns”](#returns-9)
`boolean`
Whether any copy existed.
#### Throws
[Section titled “Throws”](#throws-7)
With code `INVALID_VERTEX` when an endpoint is outside the graph.
# PathSource
Defined in: [packages/graph/src/path.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/path.ts#L4)
The part of a search result [path](/reference/knotkit/graph/functions/path/) reads: a distance and a parent per vertex.
## Properties
[Section titled “Properties”](#properties)
### distance
[Section titled “distance”](#distance)
> `readonly` **distance**: `Int32Array`<`ArrayBufferLike`> | `Float64Array`<`ArrayBufferLike`>
Defined in: [packages/graph/src/path.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/path.ts#L6)
`-1` or `Infinity` marks an unreached vertex, as `breadthFirstSearch` and `dijkstra` write it.
***
### parent
[Section titled “parent”](#parent)
> `readonly` **parent**: `Int32Array`
Defined in: [packages/graph/src/path.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/path.ts#L8)
The vertex each one was reached from, `-1` at a source.
# DijkstraStep
> **DijkstraStep** = { `kind`: `"settle"`; `vertex`: `number`; `distance`: `number`; } | { `kind`: `"relax"`; `from`: `number`; `to`: `number`; `weight`: `number`; `distance`: `number`; `improved`: `boolean`; }
Defined in: [packages/graph/src/dijkstra.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L16)
One event of a shortest-path search, in the order it happened.
* `settle`: a vertex left the frontier with its final `distance`.
* `relax`: the edge `from → to`, costing `weight`, offers `to` the total `distance` through `from`; `improved` is true when that beat the best distance known for `to`. An edge into an already settled vertex is priced and checked but not reported, since it cannot improve.
# FloydWarshallResult
> **FloydWarshallResult** = { `negativeCycle`: `false`; `distance`: `Float64Array`; } | { `negativeCycle`: `true`; `vertex`: `number`; }
Defined in: [packages/graph/src/floyd-warshall.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/floyd-warshall.ts#L10)
Every pairwise shortest distance, or a vertex on a negative cycle that makes shortest distances undefined. Exactly one of the two answers holds, and `negativeCycle` says which.
## Union Members
[Section titled “Union Members”](#union-members)
### Type Literal
[Section titled “Type Literal”](#type-literal)
{ `negativeCycle`: `false`; `distance`: `Float64Array`; }
#### negativeCycle
[Section titled “negativeCycle”](#negativecycle)
> `readonly` **negativeCycle**: `false`
#### distance
[Section titled “distance”](#distance)
> `readonly` **distance**: `Float64Array`
Row-major `n × n`: `distance[from * n + to]` is the least total weight, or `Infinity` when unreachable.
***
### Type Literal
[Section titled “Type Literal”](#type-literal-1)
{ `negativeCycle`: `true`; `vertex`: `number`; }
#### negativeCycle
[Section titled “negativeCycle”](#negativecycle-1)
> `readonly` **negativeCycle**: `true`
#### vertex
[Section titled “vertex”](#vertex)
> `readonly` **vertex**: `number`
A vertex on a cycle of negative total weight: walking the cycle from it returns to it.
# Graph
> **Graph** = [`CompressedSparseRowGraph`](/reference/knotkit/graph/interfaces/compressedsparserowgraph/) | [`MutableGraph`](/reference/knotkit/graph/interfaces/mutablegraph/) | [`AdjacencyMatrixGraph`](/reference/knotkit/graph/interfaces/adjacencymatrixgraph/)
Defined in: [packages/graph/src/graph.ts:217](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L217)
A graph over the vertices `0 … vertexCount - 1`, in one of three storage layouts that answer every shared member identically.
Every layout walks a vertex’s neighbors in ascending id, so swapping the layout changes the cost of an answer and never the answer: search results, parents, and tie-breaks included.
A union discriminated by `kind`: testing `graph.kind === 'adjacency-list'` narrows it to [MutableGraph](/reference/knotkit/graph/interfaces/mutablegraph/) and its mutators, which is how a graph from `deserializeGraph` regains them.
# GraphEdgeTuple
> **GraphEdgeTuple** = readonly \[`from`: `number`, `to`: `number`] | readonly \[`from`: `number`, `to`: `number`, `weight`: `number`]
Defined in: [packages/graph/src/graph.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L79)
One edge as a tuple: `[from, to]` on an unweighted graph, `[from, to, weight]` on a weighted one.
# GraphErrorCode
> **GraphErrorCode** = [`GraphInvalidInputErrorCode`](/reference/knotkit/graph/type-aliases/graphinvalidinputerrorcode/) | [`GraphParseErrorCode`](/reference/knotkit/graph/type-aliases/graphparseerrorcode/)
Defined in: [packages/graph/src/errors.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L52)
A machine-readable error code emitted by `knotkit/graph`.
# GraphFactory
> **GraphFactory** = (`options`) => [`Graph`](/reference/knotkit/graph/type-aliases/graph/)
Defined in: [packages/graph/src/graph.ts:220](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L220)
The signature every factory in `__GRAPH_LAYOUTS` shares.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`GraphOptions`](/reference/knotkit/graph/interfaces/graphoptions/)
## Returns
[Section titled “Returns”](#returns)
[`Graph`](/reference/knotkit/graph/type-aliases/graph/)
# GraphInvalidInputErrorCode
> **GraphInvalidInputErrorCode** = *typeof* [`GRAPH_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/graph/variables/graph_invalid_input_error_codes/)\[`number`]
Defined in: [packages/graph/src/errors.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L46)
A machine-readable invalid-input code emitted by `knotkit/graph`.
# GraphKind
> **GraphKind** = *typeof* [`GRAPH_KINDS`](/reference/knotkit/graph/variables/graph_kinds/)\[`number`]
Defined in: [packages/graph/src/graph.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L25)
The storage layout a [Graph](/reference/knotkit/graph/type-aliases/graph/) reports.
# GraphParseErrorCode
> **GraphParseErrorCode** = *typeof* [`GRAPH_PARSE_ERROR_CODES`](/reference/knotkit/graph/variables/graph_parse_error_codes/)\[`number`]
Defined in: [packages/graph/src/errors.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L49)
A machine-readable parse code emitted by `knotkit/graph`.
# TopologicalOrderResult
> **TopologicalOrderResult** = { `acyclic`: `true`; `order`: `Int32Array`; } | { `acyclic`: `false`; `cycle`: `Int32Array`; }
Defined in: [packages/graph/src/topological-order.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/topological-order.ts#L9)
A topological order, or the directed cycle that rules one out. Exactly one of the two answers holds, and `acyclic` says which.
## Union Members
[Section titled “Union Members”](#union-members)
### Type Literal
[Section titled “Type Literal”](#type-literal)
{ `acyclic`: `true`; `order`: `Int32Array`; }
#### acyclic
[Section titled “acyclic”](#acyclic)
> `readonly` **acyclic**: `true`
#### order
[Section titled “order”](#order)
> `readonly` **order**: `Int32Array`
Every vertex, each after all of its predecessors.
***
### Type Literal
[Section titled “Type Literal”](#type-literal-1)
{ `acyclic`: `false`; `cycle`: `Int32Array`; }
#### acyclic
[Section titled “acyclic”](#acyclic-1)
> `readonly` **acyclic**: `false`
#### cycle
[Section titled “cycle”](#cycle)
> `readonly` **cycle**: `Int32Array`
The vertices of one directed cycle in walk order: each has an edge to the next, and the last to the first.
# GRAPH_ERROR_CODES
> `const` **GRAPH_ERROR_CODES**: readonly [`GraphErrorCode`](/reference/knotkit/graph/type-aliases/grapherrorcode/)\[]
Defined in: [packages/graph/src/errors.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L55)
Every code emitted by `knotkit/graph`, in stable category order.
# GRAPH_INVALID_INPUT_ERROR_CODES
> `const` **GRAPH_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_VERTEX_COUNT"`, `"INVALID_VERTEX"`, `"INVALID_EDGE"`, `"INVALID_WEIGHT"`, `"MISSING_WEIGHT"`, `"UNEXPECTED_WEIGHT"`, `"INVALID_FLAG"`, `"SELF_LOOP"`, `"PARALLEL_EDGE"`, `"PARALLEL_EDGES_UNSUPPORTED"`, `"NEGATIVE_WEIGHT"`, `"DIRECTED_GRAPH_REQUIRED"`, `"UNDIRECTED_GRAPH_REQUIRED"`, `"INVALID_GRID"`, `"MAX_CAPACITY_EXCEEDED"`, `"MODIFIED_DURING_ITERATION"`, `"FOREIGN_GRAPH"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/graph/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/graph`.
# GRAPH_KINDS
> `const` **GRAPH_KINDS**: readonly \[`"compressed-sparse-row"`, `"adjacency-list"`, `"adjacency-matrix"`]
Defined in: [packages/graph/src/graph.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L18)
The storage layouts this package constructs, in the order the README and the capability record recommend them.
`compressed-sparse-row` is first: an edge set known up front is the common case, and it is smaller than the adjacency list. At degree 10 it takes 4.2 bytes per stored arc undirected and 4.4 directed, against the list’s 4.6 and 5.2, and a directed list stores every edge twice. Search speed no longer separates the two: in the package’s breadth-first-search benchmark at 100,000 vertices, the median adjacency-list search ran within 1.3 times of packed rows at degrees 1.3, 10, and 100 on JSC and V8, and within 1.11 times from degree 10 up. `adjacency-list` is the one mutable kind, for edges that arrive after construction. `adjacency-matrix` is for a small, dense, simple graph probed with `hasEdge`. `floydWarshall` runs on every layout, so an all-pairs question does not pick one.
# __GRAPH_LAYOUTS
> `const` **\_\_GRAPH_LAYOUTS**: `{ readonly [Kind in GraphKind]: (options: GraphOptions) => Extract }`
Defined in: [packages/graph/src/layouts.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/layouts.ts#L17)
Every storage layout this package constructs, keyed by the `kind` it reports, in `GRAPH_KINDS` order.
Exported so a caller, a test, or a benchmark can sweep every layout without naming one, and so a graph converts with `__GRAPH_LAYOUTS[kind]({ vertexCount, ...flags, edges: graph.edges() })`. Each row keeps its factory’s return type, so `__GRAPH_LAYOUTS['adjacency-list']` returns a `MutableGraph`. The `adjacency-matrix` row rejects `parallelEdges: true`, so a sweep over a multigraph skips it.
# GRAPH_MAX_MATRIX_BYTES
> `const` **GRAPH_MAX_MATRIX_BYTES**: `number`
Defined in: [packages/graph/src/graph.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L37)
The largest dense `n × n` buffer this package allocates, in bytes: `2 ** 28` (256 MiB). It bounds `adjacencyMatrixGraph` and `floydWarshall`.
# GRAPH_MAX_VERTEX_COUNT
> `const` **GRAPH_MAX_VERTEX_COUNT**: `number`
Defined in: [packages/graph/src/graph.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/graph.ts#L31)
The largest vertex count any graph accepts: `2 ** 31 - 1`, so every vertex fits an `Int32Array` slot and every result array can be indexed by vertex.
# GRAPH_PARSE_ERROR_CODES
> `const` **GRAPH_PARSE_ERROR_CODES**: readonly \[`"INVALID_PACKAGE_HEADER"`, `"UNKNOWN_KIND"`, `"INVALID_EDGE_SEQUENCE"`, `"INVALID_GRAPH_FLAGS"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`]
Defined in: [packages/graph/src/errors.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/errors.ts#L26)
Codes carried specifically by [GraphParseError](/reference/knotkit/graph/classes/graphparseerror/).
# knotkit/graph/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeGraphOptions](/reference/knotkit/graph/wire/interfaces/serializegraphoptions/)
## Variables
[Section titled “Variables”](#variables)
* [GRAPH_MAX_DECODE_VERTICES](/reference/knotkit/graph/wire/variables/graph_max_decode_vertices/)
## Functions
[Section titled “Functions”](#functions)
* [serializeGraph](/reference/knotkit/graph/wire/functions/serializegraph/)
* [deserializeGraph](/reference/knotkit/graph/wire/functions/deserializegraph/)
# deserializeGraph
> **deserializeGraph**(`bytes`): [`Graph`](/reference/knotkit/graph/type-aliases/graph/)
Defined in: [packages/graph/src/serialization.ts:204](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/serialization.ts#L204)
Decode bytes written by [serializeGraph](/reference/knotkit/graph/wire/functions/serializegraph/), restoring the layout, the flags, the vertex count, and the edges the artifact was serialized from.
Every edge is checked before any graph is built: endpoints in range, rows in canonical order, and contents that agree with the declared flags. The checked columns then become the graph’s storage directly, without the copy a factory makes of caller input. Allocation is bounded by [GRAPH_MAX_DECODE_VERTICES](/reference/knotkit/graph/wire/variables/graph_max_decode_vertices/) and by the payload’s length.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
[`Graph`](/reference/knotkit/graph/type-aliases/graph/)
## Throws
[Section titled “Throws”](#throws)
With a code from `GRAPH_PARSE_ERROR_CODES` when the payload is malformed, truncated, unsupported, over budget, or internally inconsistent.
## Throws
[Section titled “Throws”](#throws-1)
With code `MAX_CAPACITY_EXCEEDED` when the runtime refuses the graph’s storage.
# serializeGraph
> **serializeGraph**(`graph`, `options?`): `Uint8Array`
Defined in: [packages/graph/src/serialization.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/serialization.ts#L121)
Serialize a graph into canonical binary bytes that restore the same layout.
The payload is the graph’s `edges()` columns: sources delta-coded, targets at the smallest width that holds a vertex, and weights as little-endian `float64`, inside a `knotkit/wire` envelope whose header carries the kind, the four flags, and the producer version. Two graphs serialize to equal bytes when they have the same kind, vertex count, flags, and `edges()`, and are written by the same package version with the same `integrity` setting.
## Parameters
[Section titled “Parameters”](#parameters)
### graph
[Section titled “graph”](#graph)
[`Graph`](/reference/knotkit/graph/type-aliases/graph/)
### options?
[Section titled “options?”](#options)
[`SerializeGraphOptions`](/reference/knotkit/graph/wire/interfaces/serializegraphoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With code `FOREIGN_GRAPH` when `graph` was not produced by this package, or `SERIALIZATION_LIMIT_EXCEEDED` when it has more than [GRAPH_MAX_DECODE_VERTICES](/reference/knotkit/graph/wire/variables/graph_max_decode_vertices/) vertices.
# SerializeGraphOptions
Defined in: [packages/graph/src/serialization.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/serialization.ts#L81)
Optional behavior for binary graph serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/graph/src/serialization.ts:83](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/serialization.ts#L83)
Include a CRC-32 integrity section for accidental corruption detection.
# GRAPH_MAX_DECODE_VERTICES
> `const` **GRAPH_MAX_DECODE_VERTICES**: `number`
Defined in: [packages/graph/src/serialization.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/serialization.ts#L78)
The largest vertex count a decoder will allocate for, and the largest a serializer will write: `2 ** 24`.
Enforced in both directions on purpose. Every layout allocates per vertex, so without it a payload of a few dozen bytes could claim two billion vertices and make the decoder allocate gigabytes; and an encoder could write bytes its own decoder refuses. Edge storage needs no separate budget, because every edge occupies bytes in the payload.
# knotkit/hash
## Classes
[Section titled “Classes”](#classes)
* [HashInvalidInputError](/reference/knotkit/hash/classes/hashinvalidinputerror/)
* [HashParseError](/reference/knotkit/hash/classes/hashparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [Hash128](/reference/knotkit/hash/interfaces/hash128/)
* [HashIdentity](/reference/knotkit/hash/interfaces/hashidentity/)
* [HashState](/reference/knotkit/hash/interfaces/hashstate/)
* [ScalarHash](/reference/knotkit/hash/interfaces/scalarhash/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [HashInvalidInputErrorCode](/reference/knotkit/hash/type-aliases/hashinvalidinputerrorcode/)
* [HashParseErrorCode](/reference/knotkit/hash/type-aliases/hashparseerrorcode/)
* [HashErrorCode](/reference/knotkit/hash/type-aliases/hasherrorcode/)
* [HashKind](/reference/knotkit/hash/type-aliases/hashkind/)
* [AnyScalarHash](/reference/knotkit/hash/type-aliases/anyscalarhash/)
* [AnyHashIdentity](/reference/knotkit/hash/type-aliases/anyhashidentity/)
## Variables
[Section titled “Variables”](#variables)
* [HASH_INVALID_INPUT_ERROR_CODES](/reference/knotkit/hash/variables/hash_invalid_input_error_codes/)
* [HASH_PARSE_ERROR_CODES](/reference/knotkit/hash/variables/hash_parse_error_codes/)
* [HASH_ERROR_CODES](/reference/knotkit/hash/variables/hash_error_codes/)
* [HASH_IDENTITY_VERSION](/reference/knotkit/hash/variables/hash_identity_version/)
## Functions
[Section titled “Functions”](#functions)
* [hashFromIdentity](/reference/knotkit/hash/functions/hashfromidentity/)
* [xxh64](/reference/knotkit/hash/functions/xxh64/)
# HashInvalidInputError
Defined in: [packages/hash/src/errors.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L30)
Thrown when a caller supplies an invalid hash input or state transition.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`HashInvalidInputErrorCode`](/reference/knotkit/hash/type-aliases/hashinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new HashInvalidInputError**(`code`, `message`): `HashInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_STRING"` | `"INVALID_BYTES"` | `"INVALID_UINT32"` | `"INVALID_UINT64"` | `"INVALID_SEED"` | `"INVALID_CHUNK"` | `"INVALID_OUTPUT"` | `"INVALID_DIGEST"` | `"INPUT_TOO_LONG"` | `"STATE_FINALIZED"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`HashInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_STRING"` | `"INVALID_BYTES"` | `"INVALID_UINT32"` | `"INVALID_UINT64"` | `"INVALID_SEED"` | `"INVALID_CHUNK"` | `"INVALID_OUTPUT"` | `"INVALID_DIGEST"` | `"INPUT_TOO_LONG"` | `"STATE_FINALIZED"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/hash"`
Defined in: [packages/hash/src/errors.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L31)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# HashParseError
Defined in: [packages/hash/src/errors.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L35)
Thrown when a serialized hash identity is malformed or unsupported.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`HashParseErrorCode`](/reference/knotkit/hash/type-aliases/hashparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new HashParseError**(`code`, `message`): `HashParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"UNKNOWN_KIND"` | `"INVALID_SHAPE"` | `"INVALID_SEED"` | `"UNSUPPORTED_VERSION"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`HashParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"UNKNOWN_KIND"` | `"INVALID_SHAPE"` | `"INVALID_SEED"` | `"UNSUPPORTED_VERSION"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/hash"`
Defined in: [packages/hash/src/errors.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L36)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# hashFromIdentity
> **hashFromIdentity**(`identity`): [`ScalarHash`](/reference/knotkit/hash/interfaces/scalarhash/)
Defined in: [packages/hash/src/identity.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/identity.ts#L9)
Restore the current factory matching a parsed hash identity.
## Parameters
[Section titled “Parameters”](#parameters)
### identity
[Section titled “identity”](#identity)
[`AnyHashIdentity`](/reference/knotkit/hash/type-aliases/anyhashidentity/)
## Returns
[Section titled “Returns”](#returns)
[`ScalarHash`](/reference/knotkit/hash/interfaces/scalarhash/)
# xxh64
> **xxh64**(`seed?`): [`ScalarHash`](/reference/knotkit/hash/interfaces/scalarhash/)<`"xxh64"`, `bigint`, `bigint`>
Defined in: [packages/hash/src/xxh64.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/xxh64.ts#L55)
Create an XXH64 factory with an unsigned 64-bit seed.
XXH64 is non-cryptographic and is unsuitable for passwords, signatures, MACs, secret-derived identifiers, or hostile-input collision resistance.
## Parameters
[Section titled “Parameters”](#parameters)
### seed?
[Section titled “seed?”](#seed)
`bigint` = `0n`
## Returns
[Section titled “Returns”](#returns)
[`ScalarHash`](/reference/knotkit/hash/interfaces/scalarhash/)<`"xxh64"`, `bigint`, `bigint`>
# Hash128
Defined in: [packages/hash/src/internal/scalar-hash.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L12)
## Properties
[Section titled “Properties”](#properties)
### high
[Section titled “high”](#high)
> `readonly` **high**: `bigint`
Defined in: [packages/hash/src/internal/scalar-hash.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L13)
***
### low
[Section titled “low”](#low)
> `readonly` **low**: `bigint`
Defined in: [packages/hash/src/internal/scalar-hash.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L14)
# HashIdentity
Defined in: [packages/hash/src/internal/scalar-hash.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L17)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`ScalarHash`](/reference/knotkit/hash/interfaces/scalarhash/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* `string`
### Seed
[Section titled “Seed”](#seed)
`Seed` *extends* `number` | `bigint`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind-1)
> `readonly` **kind**: `Kind`
Defined in: [packages/hash/src/internal/scalar-hash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L18)
***
### version
[Section titled “version”](#version)
> `readonly` **version**: `string`
Defined in: [packages/hash/src/internal/scalar-hash.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L19)
***
### seed
[Section titled “seed”](#seed-1)
> `readonly` **seed**: `Seed`
Defined in: [packages/hash/src/internal/scalar-hash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L20)
# HashState
Defined in: [packages/hash/src/internal/scalar-hash.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L23)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Output
[Section titled “Output”](#output)
`Output`
## Methods
[Section titled “Methods”](#methods)
### update()
[Section titled “update()”](#update)
> **update**(`chunk`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L24)
#### Parameters
[Section titled “Parameters”](#parameters)
##### chunk
[Section titled “chunk”](#chunk)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`void`
***
### digest()
[Section titled “digest()”](#digest)
> **digest**(): `Output`
Defined in: [packages/hash/src/internal/scalar-hash.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L25)
#### Returns
[Section titled “Returns”](#returns-1)
`Output`
***
### digestInto()
[Section titled “digestInto()”](#digestinto)
> **digestInto**(`out`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L26)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### out
[Section titled “out”](#out)
`Uint32Array`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
# ScalarHash
Defined in: [packages/hash/src/internal/scalar-hash.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L29)
## Extends
[Section titled “Extends”](#extends)
* [`HashIdentity`](/reference/knotkit/hash/interfaces/hashidentity/)<`Kind`, `Seed`>
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* `string`
### Output
[Section titled “Output”](#output)
`Output`
### Seed
[Section titled “Seed”](#seed)
`Seed` *extends* `number` | `bigint`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind-1)
> `readonly` **kind**: `Kind`
Defined in: [packages/hash/src/internal/scalar-hash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L18)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HashIdentity`](/reference/knotkit/hash/interfaces/hashidentity/).[`kind`](/reference/knotkit/hash/interfaces/hashidentity/#kind-1)
***
### version
[Section titled “version”](#version)
> `readonly` **version**: `string`
Defined in: [packages/hash/src/internal/scalar-hash.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L19)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HashIdentity`](/reference/knotkit/hash/interfaces/hashidentity/).[`version`](/reference/knotkit/hash/interfaces/hashidentity/#version)
***
### seed
[Section titled “seed”](#seed-1)
> `readonly` **seed**: `Seed`
Defined in: [packages/hash/src/internal/scalar-hash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L20)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HashIdentity`](/reference/knotkit/hash/interfaces/hashidentity/).[`seed`](/reference/knotkit/hash/interfaces/hashidentity/#seed-1)
## Methods
[Section titled “Methods”](#methods)
### bytes()
[Section titled “bytes()”](#bytes)
> **bytes**(`input`): `Output`
Defined in: [packages/hash/src/internal/scalar-hash.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L33)
#### Parameters
[Section titled “Parameters”](#parameters)
##### input
[Section titled “input”](#input)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`Output`
***
### string()
[Section titled “string()”](#string)
> **string**(`input`): `Output`
Defined in: [packages/hash/src/internal/scalar-hash.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L34)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### input
[Section titled “input”](#input-1)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
`Output`
***
### uint32()
[Section titled “uint32()”](#uint32)
> **uint32**(`input`): `Output`
Defined in: [packages/hash/src/internal/scalar-hash.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L35)
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### input
[Section titled “input”](#input-2)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`Output`
***
### uint64()
[Section titled “uint64()”](#uint64)
> **uint64**(`input`): `Output`
Defined in: [packages/hash/src/internal/scalar-hash.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L36)
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### input
[Section titled “input”](#input-3)
`bigint`
#### Returns
[Section titled “Returns”](#returns-3)
`Output`
***
### bytesInto()
[Section titled “bytesInto()”](#bytesinto)
> **bytesInto**(`input`, `out`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L37)
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### input
[Section titled “input”](#input-4)
`Uint8Array`
##### out
[Section titled “out”](#out)
`Uint32Array`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
***
### stringInto()
[Section titled “stringInto()”](#stringinto)
> **stringInto**(`input`, `out`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L38)
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### input
[Section titled “input”](#input-5)
`string`
##### out
[Section titled “out”](#out-1)
`Uint32Array`
#### Returns
[Section titled “Returns”](#returns-5)
`void`
***
### uint32Into()
[Section titled “uint32Into()”](#uint32into)
> **uint32Into**(`input`, `out`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L39)
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### input
[Section titled “input”](#input-6)
`number`
##### out
[Section titled “out”](#out-2)
`Uint32Array`
#### Returns
[Section titled “Returns”](#returns-6)
`void`
***
### uint64Into()
[Section titled “uint64Into()”](#uint64into)
> **uint64Into**(`input`, `out`): `void`
Defined in: [packages/hash/src/internal/scalar-hash.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### input
[Section titled “input”](#input-7)
`bigint`
##### out
[Section titled “out”](#out-3)
`Uint32Array`
#### Returns
[Section titled “Returns”](#returns-7)
`void`
***
### create()
[Section titled “create()”](#create)
> **create**(): [`HashState`](/reference/knotkit/hash/interfaces/hashstate/)<`Output`>
Defined in: [packages/hash/src/internal/scalar-hash.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L41)
#### Returns
[Section titled “Returns”](#returns-8)
[`HashState`](/reference/knotkit/hash/interfaces/hashstate/)<`Output`>
***
### encode()
[Section titled “encode()”](#encode)
> **encode**(`output`): `Uint8Array`
Defined in: [packages/hash/src/internal/scalar-hash.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L42)
#### Parameters
[Section titled “Parameters”](#parameters-8)
##### output
[Section titled “output”](#output-1)
`Output`
#### Returns
[Section titled “Returns”](#returns-9)
`Uint8Array`
***
### encodeHex()
[Section titled “encodeHex()”](#encodehex)
> **encodeHex**(`output`): `string`
Defined in: [packages/hash/src/internal/scalar-hash.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/internal/scalar-hash.ts#L43)
#### Parameters
[Section titled “Parameters”](#parameters-9)
##### output
[Section titled “output”](#output-2)
`Output`
#### Returns
[Section titled “Returns”](#returns-10)
`string`
# AnyHashIdentity
> **AnyHashIdentity** = [`HashIdentity`](/reference/knotkit/hash/interfaces/hashidentity/)<[`HashKind`](/reference/knotkit/hash/type-aliases/hashkind/), `bigint`>
Defined in: [packages/hash/src/identity.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/identity.ts#L6)
# AnyScalarHash
> **AnyScalarHash** = `ReturnType`<*typeof* [`xxh64`](/reference/knotkit/hash/functions/xxh64/)>
Defined in: [packages/hash/src/identity.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/identity.ts#L5)
# HashErrorCode
> **HashErrorCode** = [`HashInvalidInputErrorCode`](/reference/knotkit/hash/type-aliases/hashinvalidinputerrorcode/) | [`HashParseErrorCode`](/reference/knotkit/hash/type-aliases/hashparseerrorcode/)
Defined in: [packages/hash/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L22)
# HashInvalidInputErrorCode
> **HashInvalidInputErrorCode** = *typeof* [`HASH_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/hash/variables/hash_invalid_input_error_codes/)\[`number`]
Defined in: [packages/hash/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L20)
# HashKind
> **HashKind** = `"xxh64"`
Defined in: [packages/hash/src/identity.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/identity.ts#L4)
# HashParseErrorCode
> **HashParseErrorCode** = *typeof* [`HASH_PARSE_ERROR_CODES`](/reference/knotkit/hash/variables/hash_parse_error_codes/)\[`number`]
Defined in: [packages/hash/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L21)
# HASH_ERROR_CODES
> `const` **HASH_ERROR_CODES**: readonly [`HashErrorCode`](/reference/knotkit/hash/type-aliases/hasherrorcode/)\[]
Defined in: [packages/hash/src/errors.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L25)
Every error code emitted by `knotkit/hash`, in stable category order.
# HASH_IDENTITY_VERSION
> `const` **HASH_IDENTITY_VERSION**: `"0.1.0"` = `'0.1.0'`
Defined in: [packages/hash/src/version.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/version.ts#L5)
The version of the `xxh64` hash identity. It names the mapping from inputs to digests, so it changes only when that mapping changes, never with a release. A persisted identity therefore stays readable across releases.
# HASH_INVALID_INPUT_ERROR_CODES
> `const` **HASH_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_BYTES"`, `"INVALID_STRING"`, `"INVALID_UINT32"`, `"INVALID_UINT64"`, `"INVALID_SEED"`, `"INVALID_CHUNK"`, `"INVALID_OUTPUT"`, `"INVALID_DIGEST"`, `"INPUT_TOO_LONG"`, `"STATE_FINALIZED"`]
Defined in: [packages/hash/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L4)
Every caller-state error code emitted by [HashInvalidInputError](/reference/knotkit/hash/classes/hashinvalidinputerror/).
# HASH_PARSE_ERROR_CODES
> `const` **HASH_PARSE_ERROR_CODES**: readonly \[`"INVALID_SHAPE"`, `"UNKNOWN_KIND"`, `"UNSUPPORTED_VERSION"`, `"INVALID_SEED"`]
Defined in: [packages/hash/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/errors.ts#L18)
Every serialized-identity error code emitted by [HashParseError](/reference/knotkit/hash/classes/hashparseerror/).
# knotkit/hash/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializedHashIdentity](/reference/knotkit/hash/wire/interfaces/serializedhashidentity/)
## Functions
[Section titled “Functions”](#functions)
* [serializeHashIdentity](/reference/knotkit/hash/wire/functions/serializehashidentity/)
* [deserializeHashIdentity](/reference/knotkit/hash/wire/functions/deserializehashidentity/)
# deserializeHashIdentity
> **deserializeHashIdentity**(`value`): [`AnyHashIdentity`](/reference/knotkit/hash/type-aliases/anyhashidentity/)
Defined in: [packages/hash/src/serialization.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L65)
Deserialize a canonical hash identity.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
[`AnyHashIdentity`](/reference/knotkit/hash/type-aliases/anyhashidentity/)
## Throws
[Section titled “Throws”](#throws)
HashParseError with `INVALID_SHAPE`, `UNKNOWN_KIND`, `UNSUPPORTED_VERSION`, or `INVALID_SEED` when the value is not a supported hash identity.
# serializeHashIdentity
> **serializeHashIdentity**(`identity`): [`SerializedHashIdentity`](/reference/knotkit/hash/wire/interfaces/serializedhashidentity/)
Defined in: [packages/hash/src/serialization.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L50)
Serialize a hash identity to its canonical JSON form, with the fixed key order `kind`, `version`, `seed`.
Returns the parsed value rather than JSON text, so the identity can be embedded in a larger payload; `JSON.stringify` on the result yields the canonical text, because the key order is fixed here.
## Parameters
[Section titled “Parameters”](#parameters)
### identity
[Section titled “identity”](#identity)
[`AnyHashIdentity`](/reference/knotkit/hash/type-aliases/anyhashidentity/)
## Returns
[Section titled “Returns”](#returns)
[`SerializedHashIdentity`](/reference/knotkit/hash/wire/interfaces/serializedhashidentity/)
# SerializedHashIdentity
Defined in: [packages/hash/src/serialization.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L11)
The JSON form of a hash identity: a parsed value, not JSON text. The seed is an unsigned decimal string because JSON cannot represent a 64-bit integer exactly.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"xxh64"`
Defined in: [packages/hash/src/serialization.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L12)
***
### version
[Section titled “version”](#version)
> `readonly` **version**: `string`
Defined in: [packages/hash/src/serialization.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L13)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `string`
Defined in: [packages/hash/src/serialization.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hash/src/serialization.ts#L14)
# knotkit/heap
## Classes
[Section titled “Classes”](#classes)
* [HeapInvalidInputError](/reference/knotkit/heap/classes/heapinvalidinputerror/)
* [HeapParseError](/reference/knotkit/heap/classes/heapparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [BinaryHeap](/reference/knotkit/heap/interfaces/binaryheap/)
* [DenseIntegerPriorityQueue](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
* [KHeap](/reference/knotkit/heap/interfaces/kheap/)
* [PriorityQueueSurface](/reference/knotkit/heap/interfaces/priorityqueuesurface/)
* [BinaryPriorityQueue](/reference/knotkit/heap/interfaces/binarypriorityqueue/)
* [KPriorityQueue](/reference/knotkit/heap/interfaces/kpriorityqueue/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [BinaryHeapKind](/reference/knotkit/heap/type-aliases/binaryheapkind/)
* [BinaryHeapFactory](/reference/knotkit/heap/type-aliases/binaryheapfactory/)
* [DenseIntegerPriorityQueueKind](/reference/knotkit/heap/type-aliases/denseintegerpriorityqueuekind/)
* [DenseIntegerPriorityQueueFactory](/reference/knotkit/heap/type-aliases/denseintegerpriorityqueuefactory/)
* [HeapInvalidInputErrorCode](/reference/knotkit/heap/type-aliases/heapinvalidinputerrorcode/)
* [HeapParseErrorCode](/reference/knotkit/heap/type-aliases/heapparseerrorcode/)
* [HeapErrorCode](/reference/knotkit/heap/type-aliases/heaperrorcode/)
* [KHeapKind](/reference/knotkit/heap/type-aliases/kheapkind/)
* [KHeapFactory](/reference/knotkit/heap/type-aliases/kheapfactory/)
* [Heap](/reference/knotkit/heap/type-aliases/heap/)
* [Order](/reference/knotkit/heap/type-aliases/order/)
* [BinaryPriorityQueueKind](/reference/knotkit/heap/type-aliases/binarypriorityqueuekind/)
* [KPriorityQueueKind](/reference/knotkit/heap/type-aliases/kpriorityqueuekind/)
* [BinaryPriorityQueueFactory](/reference/knotkit/heap/type-aliases/binarypriorityqueuefactory/)
* [KPriorityQueueFactory](/reference/knotkit/heap/type-aliases/kpriorityqueuefactory/)
* [PriorityQueue](/reference/knotkit/heap/type-aliases/priorityqueue/)
## Variables
[Section titled “Variables”](#variables)
* [BINARY_HEAP_KINDS](/reference/knotkit/heap/variables/binary_heap_kinds/)
* [DENSE_INTEGER_PRIORITY_QUEUE_KINDS](/reference/knotkit/heap/variables/dense_integer_priority_queue_kinds/)
* [HEAP_INVALID_INPUT_ERROR_CODES](/reference/knotkit/heap/variables/heap_invalid_input_error_codes/)
* [HEAP_PARSE_ERROR_CODES](/reference/knotkit/heap/variables/heap_parse_error_codes/)
* [HEAP_ERROR_CODES](/reference/knotkit/heap/variables/heap_error_codes/)
* [K_HEAP_KINDS](/reference/knotkit/heap/variables/k_heap_kinds/)
* [\_\_BINARY_HEAP_LAYOUTS](/reference/knotkit/heap/variables/binary_heap_layouts/)
* [\_\_K_HEAP_LAYOUTS](/reference/knotkit/heap/variables/k_heap_layouts/)
* [\_\_BINARY_PRIORITY_QUEUE_LAYOUTS](/reference/knotkit/heap/variables/binary_priority_queue_layouts/)
* [\_\_K_PRIORITY_QUEUE_LAYOUTS](/reference/knotkit/heap/variables/k_priority_queue_layouts/)
* [\_\_DENSE_INTEGER_PRIORITY_QUEUE_LAYOUTS](/reference/knotkit/heap/variables/dense_integer_priority_queue_layouts/)
* [numberOrder](/reference/knotkit/heap/variables/numberorder/)
* [stringOrder](/reference/knotkit/heap/variables/stringorder/)
* [BINARY_PRIORITY_QUEUE_KINDS](/reference/knotkit/heap/variables/binary_priority_queue_kinds/)
* [K_PRIORITY_QUEUE_KINDS](/reference/knotkit/heap/variables/k_priority_queue_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [minBinaryHeap](/reference/knotkit/heap/functions/minbinaryheap/)
* [maxBinaryHeap](/reference/knotkit/heap/functions/maxbinaryheap/)
* [denseIntegerMinPriorityQueue](/reference/knotkit/heap/functions/denseintegerminpriorityqueue/)
* [minKHeap](/reference/knotkit/heap/functions/minkheap/)
* [maxKHeap](/reference/knotkit/heap/functions/maxkheap/)
* [makeOrder](/reference/knotkit/heap/functions/makeorder/)
* [reverseOrder](/reference/knotkit/heap/functions/reverseorder/)
* [mapInputOrder](/reference/knotkit/heap/functions/mapinputorder/)
* [minPriorityQueue](/reference/knotkit/heap/functions/minpriorityqueue/)
* [maxPriorityQueue](/reference/knotkit/heap/functions/maxpriorityqueue/)
* [minKPriorityQueue](/reference/knotkit/heap/functions/minkpriorityqueue/)
* [maxKPriorityQueue](/reference/knotkit/heap/functions/maxkpriorityqueue/)
# HeapInvalidInputError
Defined in: [packages/heap/src/errors.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L77)
Thrown when a caller misuses a live structure: popping or peeking an empty one, pushing a duplicate priority-queue value, or passing an object this package did not produce.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`HeapInvalidInputErrorCode`](/reference/knotkit/heap/type-aliases/heapinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new HeapInvalidInputError**(`code`, `message`): `HeapInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"INVALID_CAPACITY"` | `"INVALID_VALUE"` | `"EMPTY"` | `"MISSING_ELEMENT_CODEC"` | `"INVALID_ARITY"` | `"DUPLICATE_VALUE"` | `"VALUE_NOT_FOUND"` | `"FOREIGN_STRUCTURE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`HeapInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"INVALID_CAPACITY"` | `"INVALID_VALUE"` | `"EMPTY"` | `"MISSING_ELEMENT_CODEC"` | `"INVALID_ARITY"` | `"DUPLICATE_VALUE"` | `"VALUE_NOT_FOUND"` | `"FOREIGN_STRUCTURE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/heap"`
Defined in: [packages/heap/src/errors.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L78)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# HeapParseError
Defined in: [packages/heap/src/errors.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L82)
Thrown when decoding a serialized heap or priority queue that is malformed or fails validation.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`HeapParseErrorCode`](/reference/knotkit/heap/type-aliases/heapparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new HeapParseError**(`code`, `message`): `HeapParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"INVALID_ELEMENT"` | `"INVALID_ARITY"` | `"DUPLICATE_VALUE"` | `"MISSING_NODES"` | `"MISSING_ENTRIES"` | `"HEAP_INVARIANT_VIOLATION"` | `"INVALID_KEY"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`HeapParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"INVALID_ELEMENT"` | `"INVALID_ARITY"` | `"DUPLICATE_VALUE"` | `"MISSING_NODES"` | `"MISSING_ENTRIES"` | `"HEAP_INVARIANT_VIOLATION"` | `"INVALID_KEY"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/heap"`
Defined in: [packages/heap/src/errors.ts:83](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L83)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# denseIntegerMinPriorityQueue
> **denseIntegerMinPriorityQueue**(`capacity`, `keyOrder`, `entries?`): [`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L63)
Allocate a binary min queue for integer values in `[0, capacity)`. Keys and positions are indexed by value. Floyd heapify preserves O(n) initial construction after allocating O(capacity) storage.
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`number`>
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
## Returns
[Section titled “Returns”](#returns)
[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_CAPACITY` for a capacity outside the nonnegative signed 32-bit range, `INVALID_VALUE` for an initial value outside the domain, or `DUPLICATE_VALUE` for a repeated initial value.
# makeOrder
> **makeOrder**<`A`>(`compare`): [`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Defined in: [packages/heap/src/order.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L22)
Build an [Order](/reference/knotkit/heap/type-aliases/order/) from a comparison function.
Short-circuits on referential equality: when `self === that` the result is `0` and `compare` is never invoked. Referential equality does not cover `NaN` (`NaN !== NaN`), so an order that must treat `NaN` as equal to itself — like [numberOrder](/reference/knotkit/heap/variables/numberorder/) — handles that inside its comparison function.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### compare
[Section titled “compare”](#compare)
(`self`, `that`) => `number`
## Returns
[Section titled “Returns”](#returns)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
# mapInputOrder
> **mapInputOrder**<`A`, `B`>(`order`, `f`): [`Order`](/reference/knotkit/heap/type-aliases/order/)<`B`>
Defined in: [packages/heap/src/order.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L43)
Derive an `Order` from an `Order` by mapping each `B` to an `A` with `f` before comparing.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
### B
[Section titled “B”](#b)
`B`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### f
[Section titled “f”](#f)
(`b`) => `A`
## Returns
[Section titled “Returns”](#returns)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`B`>
## Example
[Section titled “Example”](#example)
```ts
const byAge = mapInputOrder(numberOrder, (user: { age: number }) => user.age)
```
# maxBinaryHeap
> **maxBinaryHeap**<`A`>(`order`, `items?`): [`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
Defined in: [packages/heap/src/binary-heap.ts:358](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L358)
Create a max binary heap: the largest element per `order` is at the root, and `pop` extracts in descending order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Total ordering over the elements.
### items?
[Section titled “items?”](#items)
`Iterable`<`A`, `any`, `any`>
Optional initial elements, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
## Example
[Section titled “Example”](#example)
```ts
const heap = maxBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 50
```
# maxKHeap
> **maxKHeap**<`A`>(`k`, `order`, `items?`): [`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
Defined in: [packages/heap/src/k-heap.ts:225](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L225)
Create a max k-ary heap: the largest element per `order` is at the root, and `pop` extracts in descending order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k)
`number`
Arity: children per node. Must be a safe integer >= 2.
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Total ordering over the elements.
### items?
[Section titled “items?”](#items)
`Iterable`<`A`, `any`, `any`>
Optional initial elements, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
## Example
[Section titled “Example”](#example)
```ts
const heap = maxKHeap(4, numberOrder, [30, 1, 50, 20])
heap.peek() // 50
```
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not a safe integer of at least 2.
# maxKPriorityQueue
> **maxKPriorityQueue**<`K`, `V`>(`k`, `keyOrder`, `entries?`): [`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:723](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L723)
Create a max priority queue over a k-ary heap: same contract as [maxPriorityQueue](/reference/knotkit/heap/functions/maxpriorityqueue/), with up to `k` children per node.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k-1)
`number`
Arity: children per node. Must be a safe integer >= 2.
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
Total ordering over the keys.
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
Optional initial `[key, value]` pairs, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
## Example
[Section titled “Example”](#example)
```ts
const pq = maxKPriorityQueue(4, numberOrder, [[5, 'a'], [1, 'b'], [3, 'c']])
pq.peek() // 'a'
```
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not a safe integer of at least 2.
## Throws
[Section titled “Throws”](#throws-1)
With code `DUPLICATE_VALUE` when `entries` carries one value twice.
# maxPriorityQueue
> **maxPriorityQueue**<`K`, `V`>(`keyOrder`, `entries?`): [`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:670](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L670)
Create a max priority queue over a binary heap: the entry with the largest key per `keyOrder` is at the root, and `pop` extracts in descending key order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
Total ordering over the keys.
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
Optional initial `[key, value]` pairs, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
## Example
[Section titled “Example”](#example)
```ts
const pq = maxPriorityQueue(numberOrder, [[5, 'a'], [1, 'b'], [3, 'c']])
pq.peek() // 'a'
```
## Throws
[Section titled “Throws”](#throws)
With code `DUPLICATE_VALUE` when `entries` carries one value twice.
# minBinaryHeap
> **minBinaryHeap**<`A`>(`order`, `items?`): [`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
Defined in: [packages/heap/src/binary-heap.ts:341](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L341)
Create a min binary heap: the smallest element per `order` is at the root, and `pop` extracts in ascending order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Total ordering over the elements.
### items?
[Section titled “items?”](#items)
`Iterable`<`A`, `any`, `any`>
Optional initial elements, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
## Example
[Section titled “Example”](#example)
```ts
const heap = minBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 1
```
# minKHeap
> **minKHeap**<`A`>(`k`, `order`, `items?`): [`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
Defined in: [packages/heap/src/k-heap.ts:204](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L204)
Create a min k-ary heap: the smallest element per `order` is at the root, and `pop` extracts in ascending order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k)
`number`
Arity: children per node. Must be a safe integer >= 2.
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Total ordering over the elements.
### items?
[Section titled “items?”](#items)
`Iterable`<`A`, `any`, `any`>
Optional initial elements, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
## Example
[Section titled “Example”](#example)
```ts
const heap = minKHeap(4, numberOrder, [30, 1, 50, 20])
heap.peek() // 1
```
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not a safe integer of at least 2.
# minKPriorityQueue
> **minKPriorityQueue**<`K`, `V`>(`k`, `keyOrder`, `entries?`): [`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:696](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L696)
Create a min priority queue over a k-ary heap: same contract as [minPriorityQueue](/reference/knotkit/heap/functions/minpriorityqueue/), with up to `k` children per node.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k-1)
`number`
Arity: children per node. Must be a safe integer >= 2.
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
Total ordering over the keys.
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
Optional initial `[key, value]` pairs, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
## Example
[Section titled “Example”](#example)
```ts
const pq = minKPriorityQueue(4, numberOrder, [[5, 'a'], [1, 'b'], [3, 'c']])
pq.peek() // 'b'
```
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not a safe integer of at least 2.
## Throws
[Section titled “Throws”](#throws-1)
With code `DUPLICATE_VALUE` when `entries` carries one value twice.
# minPriorityQueue
> **minPriorityQueue**<`K`, `V`>(`keyOrder`, `entries?`): [`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:646](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L646)
Create a min priority queue over a binary heap: the entry with the smallest key per `keyOrder` is at the root, and `pop` extracts in ascending key order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
Total ordering over the keys.
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
Optional initial `[key, value]` pairs, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
## Example
[Section titled “Example”](#example)
```ts
const pq = minPriorityQueue(numberOrder, [[5, 'a'], [1, 'b'], [3, 'c']])
pq.peek() // 'b'
pq.peekEntry() // [1, 'b']
```
## Throws
[Section titled “Throws”](#throws)
With code `DUPLICATE_VALUE` when `entries` carries one value twice.
# reverseOrder
> **reverseOrder**<`A`>(`order`): [`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
Defined in: [packages/heap/src/order.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L30)
Reverse an ordering: every nonzero result flips sign, `0` stays `0`. Turns a min-comparator into a max-comparator and vice versa.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
## Returns
[Section titled “Returns”](#returns)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
# BinaryHeap
Defined in: [packages/heap/src/binary-heap.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L59)
A mutable binary heap: the extreme element under the factory’s order sits at the root, and `pop` extracts in that direction — minimum first for `'binary-min'`, maximum first for `'binary-max'`.
All implementations mutate in place. Duplicate elements are allowed; elements that compare equal have unspecified relative extraction order.
The type parameter is invariant: a mutable container both consumes and produces `A`, so `BinaryHeap` must not be assignable to `BinaryHeap` — that would allow pushing a `Cat` into a structure typed as holding only dogs.
The order supplied at construction must be total, deterministic, pure, and non-throwing, and elements must not mutate order-relevant fields while resident; violating either can leave the structure permanently inconsistent with no error signal.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binary-min"` | `"binary-max"`
Defined in: [packages/heap/src/binary-heap.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L61)
Storage layout and extraction direction. Either `'binary-min'` or `'binary-max'`.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/binary-heap.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L63)
Number of elements. O(1). The heap is empty when this is `0`.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `A`
Defined in: [packages/heap/src/binary-heap.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L71)
Return the extreme element without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/binaryheap/#push).
#### Returns
[Section titled “Returns”](#returns)
`A`
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY` when the heap is empty.
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `A`
Defined in: [packages/heap/src/binary-heap.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L80)
Remove and return the extreme element — the minimum for min kinds, the maximum for max kinds, under the factory order. O(log n).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/binaryheap/#push).
#### Returns
[Section titled “Returns”](#returns-1)
`A`
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the heap is empty.
***
### replaceRoot
[Section titled “replaceRoot”](#replaceroot)
> `readonly` **replaceRoot**: (`value`) => `A`
Defined in: [packages/heap/src/binary-heap.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L85)
Return the current root and replace it with the supplied value, preserving size. O(log n).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`A`
#### Returns
[Section titled “Returns”](#returns-2)
`A`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the heap is empty.
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`value`) => `void`
Defined in: [packages/heap/src/binary-heap.ts:96](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L96)
Insert an element and restore the heap invariant. O(log n).
Declared in property syntax on purpose: method-syntax parameters compare bivariantly, which would let `BinaryHeap` widen into `Heap` through the union’s apparent members and defeat the invariance `in out A` exists to enforce. Property syntax keeps the parameter contravariant under `strictFunctionTypes`. Every callable member is declared the same way, so the interface reads uniformly.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`A`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/binary-heap.ts:103](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L103)
Remove every element, keeping the kind, arity, and order. O(1) amortized: the backing array is truncated, never reallocated element by element.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/binaryheap/#push).
#### Returns
[Section titled “Returns”](#returns-4)
`void`
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`A`>
Defined in: [packages/heap/src/binary-heap.ts:114](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L114)
Walk the elements lazily in internal heap-array order, which is neither sorted nor insertion order: the extreme element comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space. Does not mutate the heap. The walk reads the live array, so changing the heap while a walk is open is unsupported: the walk still ends, but which elements it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/binaryheap/#push).
#### Returns
[Section titled “Returns”](#returns-5)
`IterableIterator`<`A`>
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<`A`>
Defined in: [packages/heap/src/binary-heap.ts:116](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L116)
The same walk as [values](/reference/knotkit/heap/interfaces/binaryheap/#values), as the same function, so `for (const value of heap)` works.
#### Returns
[Section titled “Returns”](#returns-6)
`IterableIterator`<`A`>
# BinaryPriorityQueue
Defined in: [packages/heap/src/priority-queue.ts:194](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L194)
A mutable indexed priority queue over a binary heap layout: the entry with the extreme key sits at the root, and `pop` extracts in that direction — minimum key first for `'binary-priority-queue-min'`, maximum key first for `'binary-priority-queue-max'`.
All implementations mutate in place. Entries with comparator-equal keys have unspecified relative extraction order. The key order supplied at construction must be total, deterministic, pure, and non-throwing, and keys must not mutate order-relevant fields while resident.
## Extends
[Section titled “Extends”](#extends)
* [`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/)<`K`, `V`>
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/priority-queue.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L80)
Number of entries. O(1). The queue is empty when this is `0`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`size`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#size)
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L89)
Return the value of the extreme entry — minimum key for min kinds, maximum key for max kinds — without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns)
`V`
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peek`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peek)
***
### peekEntry
[Section titled “peekEntry”](#peekentry)
> `readonly` **peekEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L99)
Return a fresh `readonly [key, value]` tuple for the extreme entry, without removing it. O(1). Each call allocates its own tuple, so mutating a returned tuple cannot corrupt the queue.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-1)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peekEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry)
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L108)
Remove and return the value of the extreme entry. O(log n) binary, O(k log_k n) k-ary.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-2)
`V`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`pop`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop)
***
### popEntry
[Section titled “popEntry”](#popentry)
> `readonly` **popEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L118)
Remove the extreme entry and return a fresh `readonly [key, value]` tuple for it. Same cost and freshness contract as [pop](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop) and [peekEntry](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-3)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-3)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`popEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#popentry)
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L130)
Insert a new entry and restore the heap invariant. O(log n) binary, O(k log_k n) k-ary — sift-up compares once per level.
Property syntax on purpose: method-syntax parameters compare bivariantly, which would let this interface’s implementations widen unsoundly through the `PriorityQueue` union (see the interface comment).
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-4)
With code `DUPLICATE_VALUE` when `value` is already resident. A value becomes pushable again after it is popped.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`push`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push)
***
### updateKey
[Section titled “updateKey”](#updatekey)
> `readonly` **updateKey**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:143](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L143)
Replace the key of a resident value and restore the heap invariant in the one direction the change requires. O(log n) binary, O(k log_k n) k-ary; O(1) when the new key compares equal to the old, in which case nothing moves and only the stored key (the whole entry object) is replaced.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
##### value
[Section titled “value”](#value-1)
`V`
#### Returns
[Section titled “Returns”](#returns-5)
`void`
#### Throws
[Section titled “Throws”](#throws-5)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`updateKey`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#updatekey)
***
### keyOf
[Section titled “keyOf”](#keyof)
> `readonly` **keyOf**: (`value`) => `K`
Defined in: [packages/heap/src/priority-queue.ts:152](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L152)
Return the key currently stored for `value`. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`V`
#### Returns
[Section titled “Returns”](#returns-6)
`K`
#### Throws
[Section titled “Throws”](#throws-6)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`keyOf`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#keyof)
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`value`) => `boolean`
Defined in: [packages/heap/src/priority-queue.ts:158](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L158)
Return `true` when `value` is resident. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### value
[Section titled “value”](#value-3)
`V`
#### Returns
[Section titled “Returns”](#returns-7)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`has`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#has)
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/priority-queue.ts:166](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L166)
Remove every entry, keeping the kind, arity, and key order. O(n): the value index is released along with the entries. Every previously resident value can be pushed again.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-8)
`void`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`clear`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#clear)
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L178)
Walk the entries lazily as fresh `readonly [key, value]` tuples in internal heap-array order, which is neither sorted nor insertion order: the extreme entry comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space besides each yielded tuple. Does not mutate the queue. The walk reads the live array, so changing the queue while a walk is open is unsupported: the walk still ends, but which entries it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`entries`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries)
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L180)
The same walk as [entries](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries), as the same function, so `for (const [key, value] of queue)` works.
#### Returns
[Section titled “Returns”](#returns-10)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`[iterator]`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#iterator)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binary-priority-queue-min"` | `"binary-priority-queue-max"`
Defined in: [packages/heap/src/priority-queue.ts:196](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L196)
Storage layout and extraction direction. Either `'binary-priority-queue-min'` or `'binary-priority-queue-max'`.
# DenseIntegerPriorityQueue
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L12)
A minimum queue of numeric keys over a fixed domain of integer values.
## Extends
[Section titled “Extends”](#extends)
* [`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/)<`number`, `number`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"dense-integer-priority-queue-min"`
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L13)
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L15)
Exclusive upper bound on a value. O(1).
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L21)
Insert a value by key. O(log(size + 1)).
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`number`
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_VALUE` outside the declared domain or `DUPLICATE_VALUE` while the value is resident.
#### Overrides
[Section titled “Overrides”](#overrides)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`push`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/priority-queue.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L80)
Number of entries. O(1). The queue is empty when this is `0`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`size`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#size)
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `number`
Defined in: [packages/heap/src/priority-queue.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L89)
Return the value of the extreme entry — minimum key for min kinds, maximum key for max kinds — without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peek`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peek)
***
### peekEntry
[Section titled “peekEntry”](#peekentry)
> `readonly` **peekEntry**: () => readonly \[`number`, `number`]
Defined in: [packages/heap/src/priority-queue.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L99)
Return a fresh `readonly [key, value]` tuple for the extreme entry, without removing it. O(1). Each call allocates its own tuple, so mutating a returned tuple cannot corrupt the queue.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-2)
readonly \[`number`, `number`]
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peekEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry)
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `number`
Defined in: [packages/heap/src/priority-queue.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L108)
Remove and return the value of the extreme entry. O(log n) binary, O(k log_k n) k-ary.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-3)
`number`
#### Throws
[Section titled “Throws”](#throws-3)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`pop`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop)
***
### popEntry
[Section titled “popEntry”](#popentry)
> `readonly` **popEntry**: () => readonly \[`number`, `number`]
Defined in: [packages/heap/src/priority-queue.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L118)
Remove the extreme entry and return a fresh `readonly [key, value]` tuple for it. Same cost and freshness contract as [pop](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop) and [peekEntry](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-4)
readonly \[`number`, `number`]
#### Throws
[Section titled “Throws”](#throws-4)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`popEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#popentry)
***
### updateKey
[Section titled “updateKey”](#updatekey)
> `readonly` **updateKey**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:143](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L143)
Replace the key of a resident value and restore the heap invariant in the one direction the change requires. O(log n) binary, O(k log_k n) k-ary; O(1) when the new key compares equal to the old, in which case nothing moves and only the stored key (the whole entry object) is replaced.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`number`
##### value
[Section titled “value”](#value-1)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
`void`
#### Throws
[Section titled “Throws”](#throws-5)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`updateKey`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#updatekey)
***
### keyOf
[Section titled “keyOf”](#keyof)
> `readonly` **keyOf**: (`value`) => `number`
Defined in: [packages/heap/src/priority-queue.ts:152](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L152)
Return the key currently stored for `value`. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`number`
#### Throws
[Section titled “Throws”](#throws-6)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`keyOf`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#keyof)
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`value`) => `boolean`
Defined in: [packages/heap/src/priority-queue.ts:158](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L158)
Return `true` when `value` is resident. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### value
[Section titled “value”](#value-3)
`number`
#### Returns
[Section titled “Returns”](#returns-7)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`has`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#has)
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/priority-queue.ts:166](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L166)
Remove every entry, keeping the kind, arity, and key order. O(n): the value index is released along with the entries. Every previously resident value can be pushed again.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-8)
`void`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`clear`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#clear)
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L178)
Walk the entries lazily as fresh `readonly [key, value]` tuples in internal heap-array order, which is neither sorted nor insertion order: the extreme entry comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space besides each yielded tuple. Does not mutate the queue. The walk reads the live array, so changing the queue while a walk is open is unsupported: the walk still ends, but which entries it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`entries`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries)
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L180)
The same walk as [entries](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries), as the same function, so `for (const [key, value] of queue)` works.
#### Returns
[Section titled “Returns”](#returns-10)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`[iterator]`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#iterator)
# KHeap
Defined in: [packages/heap/src/k-heap.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L50)
A mutable k-ary heap: like a binary heap, but every node holds up to `k` children. The extreme element under the factory’s order sits at the root, and `pop` extracts in that direction — minimum first for `'k-min'`, maximum first for `'k-max'`.
All implementations mutate in place. Duplicate elements are allowed; elements that compare equal have unspecified relative extraction order.
The type parameter is invariant: a mutable container both consumes and produces `A`, so `KHeap` must not be assignable to `KHeap`.
The order supplied at construction must be total, deterministic, pure, and non-throwing, and elements must not mutate order-relevant fields while resident; violating either can leave the structure permanently inconsistent with no error signal.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"k-min"` | `"k-max"`
Defined in: [packages/heap/src/k-heap.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L52)
Storage layout and extraction direction. Either `'k-min'` or `'k-max'`.
***
### arity
[Section titled “arity”](#arity)
> `readonly` **arity**: `number`
Defined in: [packages/heap/src/k-heap.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L54)
Number of children per node, fixed at construction.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/k-heap.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L56)
Number of elements. O(1). The heap is empty when this is `0`.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `A`
Defined in: [packages/heap/src/k-heap.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L64)
Return the extreme element without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/kheap/#push).
#### Returns
[Section titled “Returns”](#returns)
`A`
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY` when the heap is empty.
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `A`
Defined in: [packages/heap/src/k-heap.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L73)
Remove and return the extreme element — the minimum for min kinds, the maximum for max kinds, under the factory order. O(k log_k n).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/kheap/#push).
#### Returns
[Section titled “Returns”](#returns-1)
`A`
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the heap is empty.
***
### replaceRoot
[Section titled “replaceRoot”](#replaceroot)
> `readonly` **replaceRoot**: (`value`) => `A`
Defined in: [packages/heap/src/k-heap.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L78)
Return the current root and replace it with the supplied value, preserving size. O(k log_k n).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`A`
#### Returns
[Section titled “Returns”](#returns-2)
`A`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the heap is empty.
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`value`) => `void`
Defined in: [packages/heap/src/k-heap.ts:88](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L88)
Insert an element and restore the heap invariant. O(log_k n) — sift-up compares once per level, and a k-ary tree has fewer levels than a binary one.
Declared in property syntax for the same reason as `BinaryHeap#push`: method-syntax bivariance would let `KHeap` widen into `Heap` through the union’s apparent members.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`A`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/k-heap.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L95)
Remove every element, keeping the kind, arity, and order. O(1): the backing array is truncated.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/kheap/#push).
#### Returns
[Section titled “Returns”](#returns-4)
`void`
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`A`>
Defined in: [packages/heap/src/k-heap.ts:106](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L106)
Walk the elements lazily in internal heap-array order, which is neither sorted nor insertion order: the extreme element comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space. Does not mutate the heap. The walk reads the live array, so changing the heap while a walk is open is unsupported: the walk still ends, but which elements it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/kheap/#push).
#### Returns
[Section titled “Returns”](#returns-5)
`IterableIterator`<`A`>
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<`A`>
Defined in: [packages/heap/src/k-heap.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L108)
The same walk as [values](/reference/knotkit/heap/interfaces/kheap/#values), as the same function, so `for (const value of heap)` works.
#### Returns
[Section titled “Returns”](#returns-6)
`IterableIterator`<`A`>
# KPriorityQueue
Defined in: [packages/heap/src/priority-queue.ts:205](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L205)
A mutable indexed priority queue over a k-ary heap layout: same contract as [BinaryPriorityQueue](/reference/knotkit/heap/interfaces/binarypriorityqueue/), with up to `k` children per node. Flatter tree, fewer sift levels, more comparisons per sift-down level — the same tradeoff `KHeap` documents.
## Extends
[Section titled “Extends”](#extends)
* [`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/)<`K`, `V`>
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/priority-queue.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L80)
Number of entries. O(1). The queue is empty when this is `0`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`size`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#size)
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L89)
Return the value of the extreme entry — minimum key for min kinds, maximum key for max kinds — without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns)
`V`
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peek`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peek)
***
### peekEntry
[Section titled “peekEntry”](#peekentry)
> `readonly` **peekEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L99)
Return a fresh `readonly [key, value]` tuple for the extreme entry, without removing it. O(1). Each call allocates its own tuple, so mutating a returned tuple cannot corrupt the queue.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-1)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`peekEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry)
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L108)
Remove and return the value of the extreme entry. O(log n) binary, O(k log_k n) k-ary.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-2)
`V`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`pop`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop)
***
### popEntry
[Section titled “popEntry”](#popentry)
> `readonly` **popEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L118)
Remove the extreme entry and return a fresh `readonly [key, value]` tuple for it. Same cost and freshness contract as [pop](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop) and [peekEntry](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-3)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-3)
With code `EMPTY` when the queue is empty.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`popEntry`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#popentry)
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L130)
Insert a new entry and restore the heap invariant. O(log n) binary, O(k log_k n) k-ary — sift-up compares once per level.
Property syntax on purpose: method-syntax parameters compare bivariantly, which would let this interface’s implementations widen unsoundly through the `PriorityQueue` union (see the interface comment).
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-4)
With code `DUPLICATE_VALUE` when `value` is already resident. A value becomes pushable again after it is popped.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`push`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push)
***
### updateKey
[Section titled “updateKey”](#updatekey)
> `readonly` **updateKey**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:143](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L143)
Replace the key of a resident value and restore the heap invariant in the one direction the change requires. O(log n) binary, O(k log_k n) k-ary; O(1) when the new key compares equal to the old, in which case nothing moves and only the stored key (the whole entry object) is replaced.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
##### value
[Section titled “value”](#value-1)
`V`
#### Returns
[Section titled “Returns”](#returns-5)
`void`
#### Throws
[Section titled “Throws”](#throws-5)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`updateKey`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#updatekey)
***
### keyOf
[Section titled “keyOf”](#keyof)
> `readonly` **keyOf**: (`value`) => `K`
Defined in: [packages/heap/src/priority-queue.ts:152](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L152)
Return the key currently stored for `value`. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`V`
#### Returns
[Section titled “Returns”](#returns-6)
`K`
#### Throws
[Section titled “Throws”](#throws-6)
With code `VALUE_NOT_FOUND` when `value` is not resident.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`keyOf`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#keyof)
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`value`) => `boolean`
Defined in: [packages/heap/src/priority-queue.ts:158](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L158)
Return `true` when `value` is resident. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### value
[Section titled “value”](#value-3)
`V`
#### Returns
[Section titled “Returns”](#returns-7)
`boolean`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`has`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#has)
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/priority-queue.ts:166](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L166)
Remove every entry, keeping the kind, arity, and key order. O(n): the value index is released along with the entries. Every previously resident value can be pushed again.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-8)
`void`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`clear`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#clear)
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L178)
Walk the entries lazily as fresh `readonly [key, value]` tuples in internal heap-array order, which is neither sorted nor insertion order: the extreme entry comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space besides each yielded tuple. Does not mutate the queue. The walk reads the live array, so changing the queue while a walk is open is unsupported: the walk still ends, but which entries it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`entries`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries)
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L180)
The same walk as [entries](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries), as the same function, so `for (const [key, value] of queue)` works.
#### Returns
[Section titled “Returns”](#returns-10)
`IterableIterator`\
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
[`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/).[`[iterator]`](/reference/knotkit/heap/interfaces/priorityqueuesurface/#iterator)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"k-priority-queue-min"` | `"k-priority-queue-max"`
Defined in: [packages/heap/src/priority-queue.ts:207](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L207)
Storage layout and extraction direction. Either `'k-priority-queue-min'` or `'k-priority-queue-max'`.
***
### arity
[Section titled “arity”](#arity)
> `readonly` **arity**: `number`
Defined in: [packages/heap/src/priority-queue.ts:209](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L209)
Number of children per node, fixed at construction.
# PriorityQueueSurface
Defined in: [packages/heap/src/priority-queue.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L78)
The method surface every priority queue shares, regardless of layout. `kind` and — for k-ary layouts — `arity` are added by the concrete interfaces, because they are layout facts, not method facts.
The type parameters are invariant: a mutable container both consumes and produces `K` and `V`. Every callable member is declared in property syntax so `strictFunctionTypes` keeps the parameters that mention `K` or `V` contravariant; method-syntax parameters would compare bivariantly and let, say, `BinaryPriorityQueue` widen into `PriorityQueue` through the union’s apparent members. The members whose parameters mention neither follow the same syntax so the interface reads uniformly.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
* [`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)
* [`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/heap/src/priority-queue.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L80)
Number of entries. O(1). The queue is empty when this is `0`.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L89)
Return the value of the extreme entry — minimum key for min kinds, maximum key for max kinds — without removing it. O(1).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns)
`V`
#### Throws
[Section titled “Throws”](#throws)
With code `EMPTY` when the queue is empty.
***
### peekEntry
[Section titled “peekEntry”](#peekentry)
> `readonly` **peekEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L99)
Return a fresh `readonly [key, value]` tuple for the extreme entry, without removing it. O(1). Each call allocates its own tuple, so mutating a returned tuple cannot corrupt the queue.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-1)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-1)
With code `EMPTY` when the queue is empty.
***
### pop
[Section titled “pop”](#pop)
> `readonly` **pop**: () => `V`
Defined in: [packages/heap/src/priority-queue.ts:108](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L108)
Remove and return the value of the extreme entry. O(log n) binary, O(k log_k n) k-ary.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-2)
`V`
#### Throws
[Section titled “Throws”](#throws-2)
With code `EMPTY` when the queue is empty.
***
### popEntry
[Section titled “popEntry”](#popentry)
> `readonly` **popEntry**: () => readonly \[`K`, `V`]
Defined in: [packages/heap/src/priority-queue.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L118)
Remove the extreme entry and return a fresh `readonly [key, value]` tuple for it. Same cost and freshness contract as [pop](/reference/knotkit/heap/interfaces/priorityqueuesurface/#pop) and [peekEntry](/reference/knotkit/heap/interfaces/priorityqueuesurface/#peekentry).
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-3)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-3)
With code `EMPTY` when the queue is empty.
***
### push
[Section titled “push”](#push)
> `readonly` **push**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L130)
Insert a new entry and restore the heap invariant. O(log n) binary, O(k log_k n) k-ary — sift-up compares once per level.
Property syntax on purpose: method-syntax parameters compare bivariantly, which would let this interface’s implementations widen unsoundly through the `PriorityQueue` union (see the interface comment).
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
#### Throws
[Section titled “Throws”](#throws-4)
With code `DUPLICATE_VALUE` when `value` is already resident. A value becomes pushable again after it is popped.
***
### updateKey
[Section titled “updateKey”](#updatekey)
> `readonly` **updateKey**: (`key`, `value`) => `void`
Defined in: [packages/heap/src/priority-queue.ts:143](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L143)
Replace the key of a resident value and restore the heap invariant in the one direction the change requires. O(log n) binary, O(k log_k n) k-ary; O(1) when the new key compares equal to the old, in which case nothing moves and only the stored key (the whole entry object) is replaced.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
##### value
[Section titled “value”](#value-1)
`V`
#### Returns
[Section titled “Returns”](#returns-5)
`void`
#### Throws
[Section titled “Throws”](#throws-5)
With code `VALUE_NOT_FOUND` when `value` is not resident.
***
### keyOf
[Section titled “keyOf”](#keyof)
> `readonly` **keyOf**: (`value`) => `K`
Defined in: [packages/heap/src/priority-queue.ts:152](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L152)
Return the key currently stored for `value`. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`V`
#### Returns
[Section titled “Returns”](#returns-6)
`K`
#### Throws
[Section titled “Throws”](#throws-6)
With code `VALUE_NOT_FOUND` when `value` is not resident.
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`value`) => `boolean`
Defined in: [packages/heap/src/priority-queue.ts:158](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L158)
Return `true` when `value` is resident. O(1) average.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### value
[Section titled “value”](#value-3)
`V`
#### Returns
[Section titled “Returns”](#returns-7)
`boolean`
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/heap/src/priority-queue.ts:166](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L166)
Remove every entry, keeping the kind, arity, and key order. O(n): the value index is released along with the entries. Every previously resident value can be pushed again.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-8)
`void`
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L178)
Walk the entries lazily as fresh `readonly [key, value]` tuples in internal heap-array order, which is neither sorted nor insertion order: the extreme entry comes first and every parent precedes its children. O(n) for a full walk, O(1) extra space besides each yielded tuple. Does not mutate the queue. The walk reads the live array, so changing the queue while a walk is open is unsupported: the walk still ends, but which entries it yields is unspecified.
Property syntax for the same variance reason as [push](/reference/knotkit/heap/interfaces/priorityqueuesurface/#push).
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`\
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\
Defined in: [packages/heap/src/priority-queue.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L180)
The same walk as [entries](/reference/knotkit/heap/interfaces/priorityqueuesurface/#entries), as the same function, so `for (const [key, value] of queue)` works.
#### Returns
[Section titled “Returns”](#returns-10)
`IterableIterator`\
# BinaryHeapFactory
> **BinaryHeapFactory** = <`A`>(`order`, `items?`) => [`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
Defined in: [packages/heap/src/binary-heap.ts:145](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L145)
Create a [BinaryHeap](/reference/knotkit/heap/interfaces/binaryheap/) from an order and an optional iterable of items, bulk-built in O(n) when the items are supplied.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### items?
[Section titled “items?”](#items)
`Iterable`<`A`>
## Returns
[Section titled “Returns”](#returns)
[`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`>
# BinaryHeapKind
> **BinaryHeapKind** = *typeof* [`BINARY_HEAP_KINDS`](/reference/knotkit/heap/variables/binary_heap_kinds/)\[`number`]
Defined in: [packages/heap/src/binary-heap.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L130)
Storage layouts and extraction directions of the binary heap factories.
# BinaryPriorityQueueFactory
> **BinaryPriorityQueueFactory** = <`K`, `V`>(`keyOrder`, `entries?`) => [`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:236](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L236)
Create a [BinaryPriorityQueue](/reference/knotkit/heap/interfaces/binarypriorityqueue/) from a key order and an optional iterable of entries, bulk-built in O(n) when the entries are supplied.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
## Returns
[Section titled “Returns”](#returns)
[`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`>
# BinaryPriorityQueueKind
> **BinaryPriorityQueueKind** = *typeof* [`BINARY_PRIORITY_QUEUE_KINDS`](/reference/knotkit/heap/variables/binary_priority_queue_kinds/)\[`number`]
Defined in: [packages/heap/src/priority-queue.ts:220](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L220)
Storage layouts and extraction directions of the binary priority-queue factories.
# DenseIntegerPriorityQueueFactory
> **DenseIntegerPriorityQueueFactory** = (`capacity`, `keyOrder`, `entries?`) => [`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L24)
## Parameters
[Section titled “Parameters”](#parameters)
### capacity
[Section titled “capacity”](#capacity)
`number`
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`number`>
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
## Returns
[Section titled “Returns”](#returns)
[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
# DenseIntegerPriorityQueueKind
> **DenseIntegerPriorityQueueKind** = *typeof* [`DENSE_INTEGER_PRIORITY_QUEUE_KINDS`](/reference/knotkit/heap/variables/dense_integer_priority_queue_kinds/)\[`number`]
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L9)
# Heap
> **Heap**<`A`> = [`BinaryHeap`](/reference/knotkit/heap/interfaces/binaryheap/)<`A`> | [`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
Defined in: [packages/heap/src/k-heap.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L136)
Any heap this package ships: binary or k-ary, min or max.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
# HeapErrorCode
> **HeapErrorCode** = [`HeapInvalidInputErrorCode`](/reference/knotkit/heap/type-aliases/heapinvalidinputerrorcode/) | [`HeapParseErrorCode`](/reference/knotkit/heap/type-aliases/heapparseerrorcode/)
Defined in: [packages/heap/src/errors.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L69)
A machine-readable error code emitted by `knotkit/heap`.
# HeapInvalidInputErrorCode
> **HeapInvalidInputErrorCode** = *typeof* [`HEAP_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/heap/variables/heap_invalid_input_error_codes/)\[`number`]
Defined in: [packages/heap/src/errors.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L63)
# HeapParseErrorCode
> **HeapParseErrorCode** = *typeof* [`HEAP_PARSE_ERROR_CODES`](/reference/knotkit/heap/variables/heap_parse_error_codes/)\[`number`]
Defined in: [packages/heap/src/errors.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L66)
A machine-readable parse code emitted by `knotkit/heap`.
# KHeapFactory
> **KHeapFactory** = <`A`>(`k`, `order`, `items?`) => [`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
Defined in: [packages/heap/src/k-heap.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L133)
Create a [KHeap](/reference/knotkit/heap/interfaces/kheap/) of arity `k` from an order and an optional iterable of items.
Separate from `BinaryHeapFactory` because the arity is a construction parameter rather than part of the kind: `KHeapKind` records the direction, not `k`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k)
`number`
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### items?
[Section titled “items?”](#items)
`Iterable`<`A`>
## Returns
[Section titled “Returns”](#returns)
[`KHeap`](/reference/knotkit/heap/interfaces/kheap/)<`A`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not an integer of at least 2.
# KHeapKind
> **KHeapKind** = *typeof* [`K_HEAP_KINDS`](/reference/knotkit/heap/variables/k_heap_kinds/)\[`number`]
Defined in: [packages/heap/src/k-heap.ts:120](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L120)
Storage layouts and extraction directions of the k-ary heap factories.
# KPriorityQueueFactory
> **KPriorityQueueFactory** = <`K`, `V`>(`k`, `keyOrder`, `entries?`) => [`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/priority-queue.ts:249](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L249)
Create a [KPriorityQueue](/reference/knotkit/heap/interfaces/kpriorityqueue/) of arity `k`. Separate from [BinaryPriorityQueueFactory](/reference/knotkit/heap/type-aliases/binarypriorityqueuefactory/) because the arity is a construction parameter rather than part of the kind.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### k
[Section titled “k”](#k-1)
`number`
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### entries?
[Section titled “entries?”](#entries)
`Iterable`\
## Returns
[Section titled “Returns”](#returns)
[`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_ARITY` when `k` is not an integer of at least 2.
# KPriorityQueueKind
> **KPriorityQueueKind** = *typeof* [`K_PRIORITY_QUEUE_KINDS`](/reference/knotkit/heap/variables/k_priority_queue_kinds/)\[`number`]
Defined in: [packages/heap/src/priority-queue.ts:230](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L230)
Storage layouts and extraction directions of the k-ary priority-queue factories.
# Order
> **Order**<`A`> = (`self`, `that`) => `number`
Defined in: [packages/heap/src/order.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L11)
A total ordering on values of type `A`: a negative number when `self < that`, `0` when they are equivalent, and a positive number when `self > that`. Inspired by [Effect’s Order](https://effect-ts.github.io/effect/effect/Order.ts.html).
The type parameter is contravariant: an `Order` is usable wherever an `Order` is expected (it only reads its arguments), never the other way around.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### self
[Section titled “self”](#self)
`A`
### that
[Section titled “that”](#that)
`A`
## Returns
[Section titled “Returns”](#returns)
`number`
# PriorityQueue
> **PriorityQueue**<`K`, `V`> = [`BinaryPriorityQueue`](/reference/knotkit/heap/interfaces/binarypriorityqueue/)<`K`, `V`> | [`KPriorityQueue`](/reference/knotkit/heap/interfaces/kpriorityqueue/)<`K`, `V`> | \[`K`, `V`] *extends* \[`number`, `number`] ? \[`number`, `number`] *extends* \[`K`, `V`] ? `Pick`<[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/), `"kind"` | `"capacity"`> & [`PriorityQueueSurface`](/reference/knotkit/heap/interfaces/priorityqueuesurface/)<`K`, `V`> : `never` : `never`
Defined in: [packages/heap/src/priority-queue.ts:256](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L256)
Any indexed priority queue this package ships. The dense layout requires numeric keys and values.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
# BINARY_HEAP_KINDS
> `const` **BINARY_HEAP_KINDS**: readonly \[`"binary-min"`, `"binary-max"`]
Defined in: [packages/heap/src/binary-heap.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/binary-heap.ts#L127)
Every binary-heap layout this package provides, as a runtime value.
Exported so a caller can enumerate the directions exhaustively without restating them, and so [BinaryHeapKind](/reference/knotkit/heap/type-aliases/binaryheapkind/) is derived from the list rather than duplicating it. `__BINARY_HEAP_LAYOUTS` in `layouts.ts` is the matching construction table.
# __BINARY_HEAP_LAYOUTS
> `const` **\_\_BINARY_HEAP_LAYOUTS**: `Readonly`<`Record`<[`BinaryHeapKind`](/reference/knotkit/heap/type-aliases/binaryheapkind/), [`BinaryHeapFactory`](/reference/knotkit/heap/type-aliases/binaryheapfactory/)>>
Defined in: [packages/heap/src/layouts.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/layouts.ts#L27)
Every binary heap, keyed by the `kind` a heap built from it reports.
Iterate this table instead of naming factories one by one: a property sweep, a benchmark, or a caller comparing directions covers every entry, and a direction added to `BINARY_HEAP_KINDS` fails to typecheck until it is enrolled here too.
# BINARY_PRIORITY_QUEUE_KINDS
> `const` **BINARY_PRIORITY_QUEUE_KINDS**: readonly \[`"binary-priority-queue-min"`, `"binary-priority-queue-max"`]
Defined in: [packages/heap/src/priority-queue.ts:217](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L217)
Every binary priority-queue layout this package provides, as a runtime value. `__BINARY_PRIORITY_QUEUE_LAYOUTS` in `layouts.ts` is the matching construction table.
# __BINARY_PRIORITY_QUEUE_LAYOUTS
> `const` **\_\_BINARY_PRIORITY_QUEUE_LAYOUTS**: `Readonly`<`Record`<[`BinaryPriorityQueueKind`](/reference/knotkit/heap/type-aliases/binarypriorityqueuekind/), [`BinaryPriorityQueueFactory`](/reference/knotkit/heap/type-aliases/binarypriorityqueuefactory/)>>
Defined in: [packages/heap/src/layouts.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/layouts.ts#L43)
Every binary indexed priority queue, keyed by `kind`.
# DENSE_INTEGER_PRIORITY_QUEUE_KINDS
> `const` **DENSE_INTEGER_PRIORITY_QUEUE_KINDS**: readonly \[`"dense-integer-priority-queue-min"`]
Defined in: [packages/heap/src/dense-integer-priority-queue.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/dense-integer-priority-queue.ts#L6)
# __DENSE_INTEGER_PRIORITY_QUEUE_LAYOUTS
> `const` **\_\_DENSE_INTEGER_PRIORITY_QUEUE_LAYOUTS**: `Readonly`<`Record`<[`DenseIntegerPriorityQueueKind`](/reference/knotkit/heap/type-aliases/denseintegerpriorityqueuekind/), [`DenseIntegerPriorityQueueFactory`](/reference/knotkit/heap/type-aliases/denseintegerpriorityqueuefactory/)>>
Defined in: [packages/heap/src/layouts.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/layouts.ts#L56)
Every priority queue whose value indexes a preallocated dense domain.
# HEAP_ERROR_CODES
> `const` **HEAP_ERROR_CODES**: readonly [`HeapErrorCode`](/reference/knotkit/heap/type-aliases/heaperrorcode/)\[]
Defined in: [packages/heap/src/errors.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L72)
Every code emitted by `knotkit/heap`, in stable category order.
# HEAP_INVALID_INPUT_ERROR_CODES
> `const` **HEAP_INVALID_INPUT_ERROR_CODES**: readonly \[`"EMPTY"`, `"INVALID_ARITY"`, `"INVALID_CAPACITY"`, `"INVALID_VALUE"`, `"DUPLICATE_VALUE"`, `"VALUE_NOT_FOUND"`, `"FOREIGN_STRUCTURE"`, `"MISSING_ELEMENT_CODEC"`, `"INVALID_CODEC_RESULT"`, `"NON_INJECTIVE_CODEC"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/heap/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L21)
The canonical, ordered list of machine-readable error codes emitted by `knotkit/heap`’s public API.
The list spans both throwing classes: [HeapInvalidInputError](/reference/knotkit/heap/classes/heapinvalidinputerror/) for caller-state failures (`EMPTY`, `INVALID_ARITY`, `DUPLICATE_VALUE`, `VALUE_NOT_FOUND`, `FOREIGN_STRUCTURE`) and [HeapParseError](/reference/knotkit/heap/classes/heapparseerror/) for payload failures (`INVALID_SHAPE`, `UNSUPPORTED_SCHEMA_VERSION`, `UNKNOWN_KIND`, `MISSING_NODES`, `MISSING_ENTRIES`, `HEAP_INVARIANT_VIOLATION`, `INVALID_ELEMENT`, `INVALID_KEY`, `INVALID_VALUE`). `INVALID_ARITY`, `DUPLICATE_VALUE`, and `INVALID_CODEC_RESULT` appear in both classes — rejected at factory or serialize time as invalid input, and rejected at deserialize time as malformed payloads — because the codes are scoped to the package, not to one class. `MISSING_ELEMENT_CODEC` is invalid input in both directions: an absent codec is a caller contract violation, never a property of the bytes being decoded.
# HEAP_PARSE_ERROR_CODES
> `const` **HEAP_PARSE_ERROR_CODES**: readonly \[`"INVALID_SHAPE"`, `"UNSUPPORTED_SCHEMA_VERSION"`, `"UNKNOWN_KIND"`, `"INVALID_ARITY"`, `"DUPLICATE_VALUE"`, `"MISSING_NODES"`, `"MISSING_ENTRIES"`, `"HEAP_INVARIANT_VIOLATION"`, `"INVALID_ELEMENT"`, `"INVALID_KEY"`, `"INVALID_VALUE"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`, `"INVALID_PACKAGE_HEADER"`]
Defined in: [packages/heap/src/errors.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/errors.ts#L36)
Codes carried specifically by [HeapParseError](/reference/knotkit/heap/classes/heapparseerror/).
# K_HEAP_KINDS
> `const` **K\_HEAP_KINDS**: readonly \[`"k-min"`, `"k-max"`]
Defined in: [packages/heap/src/k-heap.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/k-heap.ts#L117)
Every k-ary-heap layout this package provides, as a runtime value.
Exported for the same reason as `BINARY_HEAP_KINDS`. `__K_HEAP_LAYOUTS` in `layouts.ts` is the matching construction table.
# __K_HEAP_LAYOUTS
> `const` **\_\_K_HEAP_LAYOUTS**: `Readonly`<`Record`<[`KHeapKind`](/reference/knotkit/heap/type-aliases/kheapkind/), [`KHeapFactory`](/reference/knotkit/heap/type-aliases/kheapfactory/)>>
Defined in: [packages/heap/src/layouts.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/layouts.ts#L37)
Every k-ary heap, keyed by `kind`. Its factories take the arity first, so this table stays separate from [\_\_BINARY_HEAP_LAYOUTS](/reference/knotkit/heap/variables/binary_heap_layouts/) rather than widening both to a signature that fits neither call site.
# K_PRIORITY_QUEUE_KINDS
> `const` **K\_PRIORITY_QUEUE_KINDS**: readonly \[`"k-priority-queue-min"`, `"k-priority-queue-max"`]
Defined in: [packages/heap/src/priority-queue.ts:227](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/priority-queue.ts#L227)
Every k-ary priority-queue layout this package provides, as a runtime value. `__K_PRIORITY_QUEUE_LAYOUTS` in `layouts.ts` is the matching construction table.
# __K_PRIORITY_QUEUE_LAYOUTS
> `const` **\_\_K_PRIORITY_QUEUE_LAYOUTS**: `Readonly`<`Record`<[`KPriorityQueueKind`](/reference/knotkit/heap/type-aliases/kpriorityqueuekind/), [`KPriorityQueueFactory`](/reference/knotkit/heap/type-aliases/kpriorityqueuefactory/)>>
Defined in: [packages/heap/src/layouts.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/layouts.ts#L50)
Every k-ary indexed priority queue, keyed by `kind`. Arity-first, like [\_\_K_HEAP_LAYOUTS](/reference/knotkit/heap/variables/k_heap_layouts/).
# numberOrder
> `const` **numberOrder**: [`Order`](/reference/knotkit/heap/type-aliases/order/)<`number`>
Defined in: [packages/heap/src/order.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L61)
A total order on `number`.
`NaN` is totally ordered as greater than every other number and equal only to itself; `0` equals `-0`. Making the order total, rather than returning `0` for every `NaN` comparison the way `<`/`>` do, is what lets heaps containing `NaN` keep a coherent invariant: with the partial rule, `NaN` would compare equal to both `1` and `3` while `1 < 3`, and a sift could strand a smaller number behind it. `NaN` therefore drains last from a min heap and first from a max heap.
Under this order `-Infinity` is the least element and `NaN` the greatest, so the full chain reads `-Infinity < -0 = 0 < 1 < Infinity < NaN`.
# stringOrder
> `const` **stringOrder**: [`Order`](/reference/knotkit/heap/type-aliases/order/)<`string`>
Defined in: [packages/heap/src/order.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/order.ts#L81)
A lexicographic order on `string` by UTF-16 code unit, which is exactly what JavaScript’s `<` and `>` operators compare. Code points above the BMP therefore order by their surrogate pairs, and combining marks compare independently of the characters they modify.
# knotkit/heap/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeHeapOptions](/reference/knotkit/heap/wire/interfaces/serializeheapoptions/)
* [DeserializeHeapOptions](/reference/knotkit/heap/wire/interfaces/deserializeheapoptions/)
* [DeserializePriorityQueueOptions](/reference/knotkit/heap/wire/interfaces/deserializepriorityqueueoptions/)
* [SerializedBinaryHeap](/reference/knotkit/heap/wire/interfaces/serializedbinaryheap/)
* [SerializedKHeap](/reference/knotkit/heap/wire/interfaces/serializedkheap/)
* [SerializedBinaryPriorityQueue](/reference/knotkit/heap/wire/interfaces/serializedbinarypriorityqueue/)
* [SerializedKPriorityQueue](/reference/knotkit/heap/wire/interfaces/serializedkpriorityqueue/)
* [SerializedDenseIntegerPriorityQueue](/reference/knotkit/heap/wire/interfaces/serializeddenseintegerpriorityqueue/)
* [DeserializePriorityQueueJsonOptions](/reference/knotkit/heap/wire/interfaces/deserializepriorityqueuejsonoptions/)
* [DeserializeHeapJsonOptions](/reference/knotkit/heap/wire/interfaces/deserializeheapjsonoptions/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/)
* [SerializedHeap](/reference/knotkit/heap/wire/type-aliases/serializedheap/)
## Variables
[Section titled “Variables”](#variables)
* [HEAP_MAX_DECODE_ELEMENTS](/reference/knotkit/heap/wire/variables/heap_max_decode_elements/)
## Functions
[Section titled “Functions”](#functions)
* [serializeHeap](/reference/knotkit/heap/wire/functions/serializeheap/)
* [deserializeHeap](/reference/knotkit/heap/wire/functions/deserializeheap/)
* [serializePriorityQueue](/reference/knotkit/heap/wire/functions/serializepriorityqueue/)
* [deserializePriorityQueue](/reference/knotkit/heap/wire/functions/deserializepriorityqueue/)
* [serializePriorityQueueJson](/reference/knotkit/heap/wire/functions/serializepriorityqueuejson/)
* [deserializePriorityQueueJson](/reference/knotkit/heap/wire/functions/deserializepriorityqueuejson/)
* [serializeHeapJson](/reference/knotkit/heap/wire/functions/serializeheapjson/)
* [deserializeHeapJson](/reference/knotkit/heap/wire/functions/deserializeheapjson/)
# deserializeHeap
> **deserializeHeap**<`A`>(`value`, `order`, `options`): [`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
Defined in: [packages/heap/src/serialization/binary.ts:169](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L169)
Restore a heap from canonical binary bytes after staging and validating every node. The supplied order must match the order used at construction.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### options
[Section titled “options”](#options)
[`DeserializeHeapOptions`](/reference/knotkit/heap/wire/interfaces/deserializeheapoptions/)<`A`>
## Returns
[Section titled “Returns”](#returns)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC` when `options.codec` is absent, which is a caller contract rather than a property of the bytes.
## Throws
[Section titled “Throws”](#throws-1)
For malformed bytes, unsupported versions, invalid codec results, invalid arity, heap-invariant violations, or decode-budget violations.
# deserializeHeapJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializeHeapJson**<`A`>(`payload`, `order`): [`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
Defined in: [packages/heap/src/serialization/json.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/json.ts#L121)
Rebuild a heap from a [SerializedHeap](/reference/knotkit/heap/wire/type-aliases/serializedheap/). O(n) time: one validation pass plus one array copy — the layout is adopted exactly, never reheapified, so a restored heap drains in the same sequence as the original.
Serialization is comparator-blind: the payload carries no order, so restore re-supplies the **base order used at construction** — the direction comes from the payload’s `kind`, not from reversing the order. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a *different* order that happens to satisfy the payload’s layout is accepted, and the restored heap then follows the order actually supplied. Comparator identity is the caller’s responsibility in their envelope — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, the full heap invariant under the direction-adjusted supplied order, and — with `options` — every element; guards run before the order is ever invoked.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### A
[Section titled “A”](#a)
`A`
### Parameters
[Section titled “Parameters”](#parameters)
#### payload
[Section titled “payload”](#payload)
[`SerializedHeap`](/reference/knotkit/heap/wire/type-aliases/serializedheap/)<`A`>
A statically typed serialized heap, or decoded `unknown` paired with runtime element validation.
#### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
The base order the heap was constructed under.
### Returns
[Section titled “Returns”](#returns)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
### Throws
[Section titled “Throws”](#throws)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `nodes` array (`MISSING_NODES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an element failing `options.isElement` (`INVALID_ELEMENT`), or a parent-child pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending index).
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializeHeapJson**<`A`>(`payload`, `order`, `options`): [`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
Defined in: [packages/heap/src/serialization/json.ts:122](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/json.ts#L122)
Rebuild a heap from a [SerializedHeap](/reference/knotkit/heap/wire/type-aliases/serializedheap/). O(n) time: one validation pass plus one array copy — the layout is adopted exactly, never reheapified, so a restored heap drains in the same sequence as the original.
Serialization is comparator-blind: the payload carries no order, so restore re-supplies the **base order used at construction** — the direction comes from the payload’s `kind`, not from reversing the order. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a *different* order that happens to satisfy the payload’s layout is accepted, and the restored heap then follows the order actually supplied. Comparator identity is the caller’s responsibility in their envelope — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, the full heap invariant under the direction-adjusted supplied order, and — with `options` — every element; guards run before the order is ever invoked.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### A
[Section titled “A”](#a-1)
`A`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### payload
[Section titled “payload”](#payload-1)
`unknown`
A statically typed serialized heap, or decoded `unknown` paired with runtime element validation.
#### order
[Section titled “order”](#order-1)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
The base order the heap was constructed under.
#### options
[Section titled “options”](#options)
[`DeserializeHeapJsonOptions`](/reference/knotkit/heap/wire/interfaces/deserializeheapjsonoptions/)<`A`>
Runtime decoding options for payloads whose element type is not yet known.
### Returns
[Section titled “Returns”](#returns-1)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
### Throws
[Section titled “Throws”](#throws-1)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `nodes` array (`MISSING_NODES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an element failing `options.isElement` (`INVALID_ELEMENT`), or a parent-child pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending index).
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializeHeapJson**(`payload`, `order`): [`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`unknown`>
Defined in: [packages/heap/src/serialization/json.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/json.ts#L127)
Rebuild a heap from a [SerializedHeap](/reference/knotkit/heap/wire/type-aliases/serializedheap/). O(n) time: one validation pass plus one array copy — the layout is adopted exactly, never reheapified, so a restored heap drains in the same sequence as the original.
Serialization is comparator-blind: the payload carries no order, so restore re-supplies the **base order used at construction** — the direction comes from the payload’s `kind`, not from reversing the order. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a *different* order that happens to satisfy the payload’s layout is accepted, and the restored heap then follows the order actually supplied. Comparator identity is the caller’s responsibility in their envelope — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, the full heap invariant under the direction-adjusted supplied order, and — with `options` — every element; guards run before the order is ever invoked.
### Parameters
[Section titled “Parameters”](#parameters-2)
#### payload
[Section titled “payload”](#payload-2)
`unknown`
A statically typed serialized heap, or decoded `unknown` paired with runtime element validation.
#### order
[Section titled “order”](#order-2)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`unknown`>
The base order the heap was constructed under.
### Returns
[Section titled “Returns”](#returns-2)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`unknown`>
### Throws
[Section titled “Throws”](#throws-2)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `nodes` array (`MISSING_NODES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an element failing `options.isElement` (`INVALID_ELEMENT`), or a parent-child pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending index).
# deserializePriorityQueue
> **deserializePriorityQueue**<`K`, `V`>(`value`, `keyOrder`, `options`): [`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/serialization/binary.ts:302](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L302)
Restore a priority queue from canonical binary bytes after staging both runs, rejecting duplicate decoded values, and validating key order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### options
[Section titled “options”](#options)
[`DeserializePriorityQueueOptions`](/reference/knotkit/heap/wire/interfaces/deserializepriorityqueueoptions/)<`K`, `V`>
## Returns
[Section titled “Returns”](#returns)
[`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC` when `options.keyCodec` or `options.valueCodec` is absent, which is a caller contract rather than a property of the bytes.
## Throws
[Section titled “Throws”](#throws-1)
For malformed bytes, unsupported versions, invalid codec results, duplicate values, invalid arity, heap-invariant violations, or decode-budget violations.
# deserializePriorityQueueJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializePriorityQueueJson**(`payload`, `keyOrder`): [`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:193](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L193)
Rebuild a priority queue from a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time: one validation pass plus one entry copy — the layout is adopted exactly, never reheapified, and the value-to-index overlay is rebuilt in a single sweep.
Serialization is comparator-blind: pass the **base key order used at construction** — the direction comes from the payload’s `kind`. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a different order that happens to satisfy the payload’s layout is accepted, and the restored queue then follows the order actually supplied. Comparator identity is the caller’s responsibility — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, per-entry `[key, value]` pair shape, duplicate values (the overlay requires unique values), the full heap invariant over keys under the direction-adjusted supplied order, and — with `options` — every key and value; guards run before the order is ever invoked.
### Parameters
[Section titled “Parameters”](#parameters)
#### payload
[Section titled “payload”](#payload)
[`SerializedDenseIntegerPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializeddenseintegerpriorityqueue/)
A statically typed serialized priority queue, or decoded `unknown` paired with runtime key and value validation.
#### keyOrder
[Section titled “keyOrder”](#keyorder)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`number`>
The base key order the queue was constructed under.
### Returns
[Section titled “Returns”](#returns)
[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
### Throws
[Section titled “Throws”](#throws)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `entries` array (`MISSING_ENTRIES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an entry that is not a `[key, value]` pair (`INVALID_SHAPE`, naming the index), a key or value failing its guard (`INVALID_KEY`/`INVALID_VALUE`), a duplicate value (`DUPLICATE_VALUE`), or a parent-child key pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending entry index).
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializePriorityQueueJson**<`K`, `V`>(`payload`, `keyOrder`): [`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:197](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L197)
Rebuild a priority queue from a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time: one validation pass plus one entry copy — the layout is adopted exactly, never reheapified, and the value-to-index overlay is rebuilt in a single sweep.
Serialization is comparator-blind: pass the **base key order used at construction** — the direction comes from the payload’s `kind`. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a different order that happens to satisfy the payload’s layout is accepted, and the restored queue then follows the order actually supplied. Comparator identity is the caller’s responsibility — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, per-entry `[key, value]` pair shape, duplicate values (the overlay requires unique values), the full heap invariant over keys under the direction-adjusted supplied order, and — with `options` — every key and value; guards run before the order is ever invoked.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### K
[Section titled “K”](#k)
`K`
#### V
[Section titled “V”](#v)
`V`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### payload
[Section titled “payload”](#payload-1)
[`SerializedPriorityQueue`](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/)<`K`, `V`>
A statically typed serialized priority queue, or decoded `unknown` paired with runtime key and value validation.
#### keyOrder
[Section titled “keyOrder”](#keyorder-1)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
The base key order the queue was constructed under.
### Returns
[Section titled “Returns”](#returns-1)
[`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
### Throws
[Section titled “Throws”](#throws-1)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `entries` array (`MISSING_ENTRIES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an entry that is not a `[key, value]` pair (`INVALID_SHAPE`, naming the index), a key or value failing its guard (`INVALID_KEY`/`INVALID_VALUE`), a duplicate value (`DUPLICATE_VALUE`), or a parent-child key pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending entry index).
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializePriorityQueueJson**<`K`, `V`>(`payload`, `keyOrder`, `options`): [`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:201](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L201)
Rebuild a priority queue from a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time: one validation pass plus one entry copy — the layout is adopted exactly, never reheapified, and the value-to-index overlay is rebuilt in a single sweep.
Serialization is comparator-blind: pass the **base key order used at construction** — the direction comes from the payload’s `kind`. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a different order that happens to satisfy the payload’s layout is accepted, and the restored queue then follows the order actually supplied. Comparator identity is the caller’s responsibility — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, per-entry `[key, value]` pair shape, duplicate values (the overlay requires unique values), the full heap invariant over keys under the direction-adjusted supplied order, and — with `options` — every key and value; guards run before the order is ever invoked.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### K
[Section titled “K”](#k-1)
`K`
#### V
[Section titled “V”](#v-1)
`V`
### Parameters
[Section titled “Parameters”](#parameters-2)
#### payload
[Section titled “payload”](#payload-2)
`unknown`
A statically typed serialized priority queue, or decoded `unknown` paired with runtime key and value validation.
#### keyOrder
[Section titled “keyOrder”](#keyorder-2)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
The base key order the queue was constructed under.
#### options
[Section titled “options”](#options)
[`DeserializePriorityQueueJsonOptions`](/reference/knotkit/heap/wire/interfaces/deserializepriorityqueuejsonoptions/)<`K`, `V`>
Runtime decoding options for payloads whose key and value types are not yet known.
### Returns
[Section titled “Returns”](#returns-2)
[`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
### Throws
[Section titled “Throws”](#throws-2)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `entries` array (`MISSING_ENTRIES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an entry that is not a `[key, value]` pair (`INVALID_SHAPE`, naming the index), a key or value failing its guard (`INVALID_KEY`/`INVALID_VALUE`), a duplicate value (`DUPLICATE_VALUE`), or a parent-child key pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending entry index).
## Call Signature
[Section titled “Call Signature”](#call-signature-3)
> **deserializePriorityQueueJson**(`payload`, `keyOrder`): [`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/) | [`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`unknown`, `unknown`>
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:206](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L206)
Rebuild a priority queue from a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time: one validation pass plus one entry copy — the layout is adopted exactly, never reheapified, and the value-to-index overlay is rebuilt in a single sweep.
Serialization is comparator-blind: pass the **base key order used at construction** — the direction comes from the payload’s `kind`. Round-trip fidelity holds when the re-supplied order is semantically equivalent to the original; a different order that happens to satisfy the payload’s layout is accepted, and the restored queue then follows the order actually supplied. Comparator identity is the caller’s responsibility — a documented limitation, not a validated fact.
Validation covers shape, kind, arity, per-entry `[key, value]` pair shape, duplicate values (the overlay requires unique values), the full heap invariant over keys under the direction-adjusted supplied order, and — with `options` — every key and value; guards run before the order is ever invoked.
### Parameters
[Section titled “Parameters”](#parameters-3)
#### payload
[Section titled “payload”](#payload-3)
`unknown`
A statically typed serialized priority queue, or decoded `unknown` paired with runtime key and value validation.
#### keyOrder
[Section titled “keyOrder”](#keyorder-3)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`unknown`>
The base key order the queue was constructed under.
### Returns
[Section titled “Returns”](#returns-3)
[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/) | [`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`unknown`, `unknown`>
### Throws
[Section titled “Throws”](#throws-3)
When the payload is malformed or fails validation: not an object (`INVALID_SHAPE`), a missing or unsupported schema version (`UNSUPPORTED_SCHEMA_VERSION`), an unknown or cross-family `kind` (`UNKNOWN_KIND`), a missing or mistyped `entries` array (`MISSING_ENTRIES`), an unsafe or missing k-ary `arity` (`INVALID_ARITY`), an entry that is not a `[key, value]` pair (`INVALID_SHAPE`, naming the index), a key or value failing its guard (`INVALID_KEY`/`INVALID_VALUE`), a duplicate value (`DUPLICATE_VALUE`), or a parent-child key pair violating the heap invariant (`HEAP_INVARIANT_VIOLATION`, naming the offending entry index).
# serializeHeap
> **serializeHeap**<`A`>(`heap`, `codec`, `options?`): `Uint8Array`
Defined in: [packages/heap/src/serialization/binary.ts:141](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L141)
Serialize a heap’s exact internal node order into canonical binary bytes. The caller-supplied order remains outside the artifact.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### heap
[Section titled “heap”](#heap)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`A`>
### options?
[Section titled “options?”](#options)
[`SerializeHeapOptions`](/reference/knotkit/heap/wire/interfaces/serializeheapoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_STRUCTURE`, `MISSING_ELEMENT_CODEC`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the input cannot be represented.
# serializeHeapJson
> **serializeHeapJson**<`A`>(`heap`): [`SerializedHeap`](/reference/knotkit/heap/wire/type-aliases/serializedheap/)<`A`>
Defined in: [packages/heap/src/serialization/json.ts:70](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/json.ts#L70)
Capture a heap as a [SerializedHeap](/reference/knotkit/heap/wire/type-aliases/serializedheap/). O(n) time and space — a copy of the internal node array plus the discriminants, nothing more.
The snapshot is faithful, not canonical: it records the exact internal layout, never the order function (functions do not serialize — restoring re-supplies it, see [deserializeHeapJson](/reference/knotkit/heap/wire/functions/deserializeheapjson/)), and never a reheapified equivalent. The nodes are copied defensively, so later mutation of either the heap or the payload cannot reach the other.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### heap
[Section titled “heap”](#heap)
[`Heap`](/reference/knotkit/heap/type-aliases/heap/)<`A`>
## Returns
[Section titled “Returns”](#returns)
[`SerializedHeap`](/reference/knotkit/heap/wire/type-aliases/serializedheap/)<`A`>
## Throws
[Section titled “Throws”](#throws)
With code `FOREIGN_STRUCTURE` when `heap` was not produced by this package’s heap factories — including a priority queue passed by mistake, which carries the package’s state bridge but not a heap `kind`.
# serializePriorityQueue
> **serializePriorityQueue**<`K`, `V`>(`queue`, `keyCodec`, `valueCodec`, `options?`): `Uint8Array`
Defined in: [packages/heap/src/serialization/binary.ts:221](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L221)
Serialize a priority queue into parallel key and value runs in exact internal entry order. The key order remains outside the artifact.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### queue
[Section titled “queue”](#queue)
[`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
### keyCodec
[Section titled “keyCodec”](#keycodec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`K`>
### valueCodec
[Section titled “valueCodec”](#valuecodec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`V`>
### options?
[Section titled “options?”](#options)
[`SerializeHeapOptions`](/reference/knotkit/heap/wire/interfaces/serializeheapoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_STRUCTURE`, `MISSING_ELEMENT_CODEC`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the input cannot be represented.
# serializePriorityQueueJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **serializePriorityQueueJson**(`queue`): [`SerializedDenseIntegerPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializeddenseintegerpriorityqueue/)
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L133)
Capture a priority queue as a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time and space — the internal entries copied to fresh `[key, value]` tuples plus the discriminants. Same faithful-not-canonical and defensive-copy contract as `serializeBinaryHeap`/`serializeKHeap`; the key order is never captured.
### Parameters
[Section titled “Parameters”](#parameters)
#### queue
[Section titled “queue”](#queue)
[`DenseIntegerPriorityQueue`](/reference/knotkit/heap/interfaces/denseintegerpriorityqueue/)
### Returns
[Section titled “Returns”](#returns)
[`SerializedDenseIntegerPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializeddenseintegerpriorityqueue/)
### Throws
[Section titled “Throws”](#throws)
With code `FOREIGN_STRUCTURE` when `queue` was not produced by this package’s priority-queue factories — including a heap passed by mistake.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **serializePriorityQueueJson**<`K`, `V`>(`queue`): [`SerializedPriorityQueue`](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/)<`K`, `V`>
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:134](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L134)
Capture a priority queue as a [SerializedPriorityQueue](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/). O(n) time and space — the internal entries copied to fresh `[key, value]` tuples plus the discriminants. Same faithful-not-canonical and defensive-copy contract as `serializeBinaryHeap`/`serializeKHeap`; the key order is never captured.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### K
[Section titled “K”](#k)
`K`
#### V
[Section titled “V”](#v)
`V`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### queue
[Section titled “queue”](#queue-1)
[`PriorityQueue`](/reference/knotkit/heap/type-aliases/priorityqueue/)<`K`, `V`>
### Returns
[Section titled “Returns”](#returns-1)
[`SerializedPriorityQueue`](/reference/knotkit/heap/wire/type-aliases/serializedpriorityqueue/)<`K`, `V`>
### Throws
[Section titled “Throws”](#throws-1)
With code `FOREIGN_STRUCTURE` when `queue` was not produced by this package’s priority-queue factories — including a heap passed by mistake.
# DeserializeHeapJsonOptions
Defined in: [packages/heap/src/serialization/families/support.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/support.ts#L18)
Runtime decoding options for heap payloads whose element type is not yet known.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### isElement
[Section titled “isElement”](#iselement)
> `readonly` **isElement**: (`value`) => `value is A`
Defined in: [packages/heap/src/serialization/families/support.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/support.ts#L20)
Prove the type of every decoded element.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is A`
# DeserializeHeapOptions
Defined in: [packages/heap/src/serialization/binary.ts:87](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L87)
Runtime inputs for decoding a heap’s generic node run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### codec
[Section titled “codec”](#codec)
> `readonly` **codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`A`>
Defined in: [packages/heap/src/serialization/binary.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L89)
Codec matching the one used to serialize the node run.
***
### isElement?
[Section titled “isElement?”](#iselement)
> `readonly` `optional` **isElement?**: (`value`) => `value is A`
Defined in: [packages/heap/src/serialization/binary.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L91)
Optional validation applied to every decoded node.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is A`
# DeserializePriorityQueueJsonOptions
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L80)
Runtime decoding options for priority-queue payloads whose key and value types are not yet known.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### isKey
[Section titled “isKey”](#iskey)
> `readonly` **isKey**: (`value`) => `value is K`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L82)
Prove the type of every decoded key.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is K`
***
### isValue
[Section titled “isValue”](#isvalue)
> `readonly` **isValue**: (`value`) => `value is V`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:84](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L84)
Prove the type of every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`unknown`
#### Returns
[Section titled “Returns”](#returns-1)
`value is V`
# DeserializePriorityQueueOptions
Defined in: [packages/heap/src/serialization/binary.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L95)
Runtime inputs for decoding a priority queue’s parallel key and value runs.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### keyCodec
[Section titled “keyCodec”](#keycodec)
> `readonly` **keyCodec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`K`>
Defined in: [packages/heap/src/serialization/binary.ts:97](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L97)
Codec matching the one used to serialize keys.
***
### valueCodec
[Section titled “valueCodec”](#valuecodec)
> `readonly` **valueCodec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`V`>
Defined in: [packages/heap/src/serialization/binary.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L99)
Codec matching the one used to serialize values.
***
### isKey?
[Section titled “isKey?”](#iskey)
> `readonly` `optional` **isKey?**: (`value`) => `value is K`
Defined in: [packages/heap/src/serialization/binary.ts:101](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L101)
Optional validation applied to every decoded key.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is K`
***
### isValue?
[Section titled “isValue?”](#isvalue)
> `readonly` `optional` **isValue?**: (`value`) => `value is V`
Defined in: [packages/heap/src/serialization/binary.ts:103](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L103)
Optional validation applied to every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`unknown`
#### Returns
[Section titled “Returns”](#returns-1)
`value is V`
# SerializedBinaryHeap
Defined in: [packages/heap/src/serialization/families/binary-heap.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/binary-heap.ts#L23)
A plain, inert snapshot of a binary heap. It holds no behavior and no reference to the heap it came from, so it can be stored, compared, structurally cloned, or sent through `postMessage`. It survives `JSON.stringify` when the elements themselves do.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/heap/src/serialization/families/binary-heap.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/binary-heap.ts#L25)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binary-min"` | `"binary-max"`
Defined in: [packages/heap/src/serialization/families/binary-heap.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/binary-heap.ts#L27)
The storage layout and extraction direction to restore.
***
### nodes
[Section titled “nodes”](#nodes)
> `readonly` **nodes**: readonly `A`\[]
Defined in: [packages/heap/src/serialization/families/binary-heap.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/binary-heap.ts#L29)
The internal node array, in exact internal heap order.
# SerializedBinaryPriorityQueue
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L37)
A plain, inert snapshot of a binary priority queue: the internal entry array as `[key, value]` tuples, in exact internal heap order. Values are unique across the array; duplicate keys are as legal as on a live queue.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L39)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binary-priority-queue-min"` | `"binary-priority-queue-max"`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L41)
The storage layout and extraction direction to restore.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: readonly (readonly \[`K`, `V`])\[]
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L43)
The internal entries as `[key, value]` tuples, in exact internal heap order.
# SerializedDenseIntegerPriorityQueue
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:62](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L62)
Exact heap order and the declared numeric domain of a dense queue.
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L63)
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"dense-integer-priority-queue-min"`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L64)
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L65)
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: readonly (readonly \[`number`, `number`])\[]
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L66)
# SerializedKHeap
Defined in: [packages/heap/src/serialization/families/k-heap.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/k-heap.ts#L20)
A plain, inert snapshot of a k-ary heap, adding the layout’s `arity`. Restoring requires the same arity the heap was built with; it is validated as a safe integer of at least 2 exactly like the factory argument.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/heap/src/serialization/families/k-heap.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/k-heap.ts#L22)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"k-min"` | `"k-max"`
Defined in: [packages/heap/src/serialization/families/k-heap.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/k-heap.ts#L24)
The storage layout and extraction direction to restore.
***
### arity
[Section titled “arity”](#arity)
> `readonly` **arity**: `number`
Defined in: [packages/heap/src/serialization/families/k-heap.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/k-heap.ts#L26)
Children per node, as the factory fixed it.
***
### nodes
[Section titled “nodes”](#nodes)
> `readonly` **nodes**: readonly `A`\[]
Defined in: [packages/heap/src/serialization/families/k-heap.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/k-heap.ts#L28)
The internal node array, in exact internal heap order.
# SerializedKPriorityQueue
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L50)
A plain, inert snapshot of a k-ary priority queue, adding the layout’s `arity` to the binary shape.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L52)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"k-priority-queue-min"` | `"k-priority-queue-max"`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L54)
The storage layout and extraction direction to restore.
***
### arity
[Section titled “arity”](#arity)
> `readonly` **arity**: `number`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L56)
Children per node, as the factory fixed it.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: readonly (readonly \[`K`, `V`])\[]
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L58)
The internal entries as `[key, value]` tuples, in exact internal heap order.
# SerializeHeapOptions
Defined in: [packages/heap/src/serialization/binary.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L81)
Options shared by heap and priority-queue binary serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/heap/src/serialization/binary.ts:83](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/binary.ts#L83)
Include a CRC-32 integrity section for accidental corruption detection.
# SerializedHeap
> **SerializedHeap**<`A`> = [`SerializedBinaryHeap`](/reference/knotkit/heap/wire/interfaces/serializedbinaryheap/)<`A`> | [`SerializedKHeap`](/reference/knotkit/heap/wire/interfaces/serializedkheap/)<`A`>
Defined in: [packages/heap/src/serialization/json.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/json.ts#L53)
Any serialized heap this package produces: binary or k-ary, min or max.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
# SerializedPriorityQueue
> **SerializedPriorityQueue**<`K`, `V`> = [`SerializedBinaryPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializedbinarypriorityqueue/)<`K`, `V`> | [`SerializedKPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializedkpriorityqueue/)<`K`, `V`> | \[`K`, `V`] *extends* \[`number`, `number`] ? \[`number`, `number`] *extends* \[`K`, `V`] ? [`SerializedDenseIntegerPriorityQueue`](/reference/knotkit/heap/wire/interfaces/serializeddenseintegerpriorityqueue/) : `never` : `never`
Defined in: [packages/heap/src/serialization/families/priority-queue.ts:70](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/priority-queue.ts#L70)
Any serialized priority queue for the supplied key and value types.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
# HEAP_MAX_DECODE_ELEMENTS
> `const` **HEAP_MAX_DECODE_ELEMENTS**: `1000000` = `1_000_000`
Defined in: [packages/heap/src/serialization/families/support.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/heap/src/serialization/families/support.ts#L15)
Maximum staged node count or allocated dense domain in a heap decoder.
# knotkit/hypothesis-test
## Classes
[Section titled “Classes”](#classes)
* [HypothesisTestInvalidInputError](/reference/knotkit/hypothesis-test/classes/hypothesistestinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [BinomialTestOptions](/reference/knotkit/hypothesis-test/interfaces/binomialtestoptions/)
* [BinomialTestResult](/reference/knotkit/hypothesis-test/interfaces/binomialtestresult/)
* [ChiSquaredGoodnessOfFitTestOptions](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestoptions/)
* [ChiSquaredGoodnessOfFitTestResult](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestresult/)
* [FisherExactTestOptions](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestoptions/)
* [FisherExactTestResult](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestresult/)
* [HypothesisTestAlternativeOptions](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
* [HypothesisTestResult](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/)
* [AlternativeHypothesisTestResult](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
* [KolmogorovSmirnovTestOptions](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestoptions/)
* [KolmogorovSmirnovTestResult](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestresult/)
* [KruskalWallisTestResult](/reference/knotkit/hypothesis-test/interfaces/kruskalwallistestresult/)
* [MannWhitneyUTestOptions](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestoptions/)
* [MannWhitneyUTestResult](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestresult/)
* [OneSampleTTestOptions](/reference/knotkit/hypothesis-test/interfaces/onesamplettestoptions/)
* [OneSampleTTestResult](/reference/knotkit/hypothesis-test/interfaces/onesamplettestresult/)
* [OneWayAnovaResult](/reference/knotkit/hypothesis-test/interfaces/onewayanovaresult/)
* [PairedTTestOptions](/reference/knotkit/hypothesis-test/interfaces/pairedttestoptions/)
* [PairedTTestResult](/reference/knotkit/hypothesis-test/interfaces/pairedttestresult/)
* [TTestResult](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
* [TwoSampleKolmogorovSmirnovTestOptions](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestoptions/)
* [TwoSampleKolmogorovSmirnovTestResult](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestresult/)
* [TwoSampleTTestOptions](/reference/knotkit/hypothesis-test/interfaces/twosamplettestoptions/)
* [TwoSampleTTestResult](/reference/knotkit/hypothesis-test/interfaces/twosamplettestresult/)
* [WelchTTestOptions](/reference/knotkit/hypothesis-test/interfaces/welchttestoptions/)
* [WelchTTestResult](/reference/knotkit/hypothesis-test/interfaces/welchttestresult/)
* [WilcoxonSignedRankTestOptions](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestoptions/)
* [WilcoxonSignedRankTestResult](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestresult/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [HypothesisTestInvalidInputErrorCode](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestinvalidinputerrorcode/)
* [HypothesisTestErrorCode](/reference/knotkit/hypothesis-test/type-aliases/hypothesistesterrorcode/)
* [FisherExactTestTable](/reference/knotkit/hypothesis-test/type-aliases/fisherexacttesttable/)
* [HypothesisTestAlternative](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestalternative/)
* [HypothesisTestMethod](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
* [HypothesisTestMethodOption](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethodoption/)
## Variables
[Section titled “Variables”](#variables)
* [HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES](/reference/knotkit/hypothesis-test/variables/hypothesis_test_invalid_input_error_codes/)
* [HYPOTHESIS_TEST_ERROR_CODES](/reference/knotkit/hypothesis-test/variables/hypothesis_test_error_codes/)
* [HYPOTHESIS_TEST_ALTERNATIVES](/reference/knotkit/hypothesis-test/variables/hypothesis_test_alternatives/)
## Functions
[Section titled “Functions”](#functions)
* [binomialTest](/reference/knotkit/hypothesis-test/functions/binomialtest/)
* [chiSquaredGoodnessOfFitTest](/reference/knotkit/hypothesis-test/functions/chisquaredgoodnessoffittest/)
* [fisherExactTest](/reference/knotkit/hypothesis-test/functions/fisherexacttest/)
* [kolmogorovSmirnovTest](/reference/knotkit/hypothesis-test/functions/kolmogorovsmirnovtest/)
* [kruskalWallisTest](/reference/knotkit/hypothesis-test/functions/kruskalwallistest/)
* [mannWhitneyUTest](/reference/knotkit/hypothesis-test/functions/mannwhitneyutest/)
* [oneSampleTTest](/reference/knotkit/hypothesis-test/functions/onesamplettest/)
* [oneWayAnova](/reference/knotkit/hypothesis-test/functions/onewayanova/)
* [pairedTTest](/reference/knotkit/hypothesis-test/functions/pairedttest/)
* [twoSampleKolmogorovSmirnovTest](/reference/knotkit/hypothesis-test/functions/twosamplekolmogorovsmirnovtest/)
* [twoSampleTTest](/reference/knotkit/hypothesis-test/functions/twosamplettest/)
* [welchTTest](/reference/knotkit/hypothesis-test/functions/welchttest/)
* [wilcoxonSignedRankTest](/reference/knotkit/hypothesis-test/functions/wilcoxonsignedranktest/)
## References
[Section titled “References”](#references)
### Probability
[Section titled “Probability”](#probability)
Re-exports [Probability](/reference/knotkit/distribution/variables/probability/)
# HypothesisTestInvalidInputError
Defined in: [packages/hypothesis-test/src/errors.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L27)
An input that cannot describe a test supported by this package.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`HypothesisTestInvalidInputErrorCode`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new HypothesisTestInvalidInputError**(`code`, `message`): `HypothesisTestInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_COUNT"` | `"INVALID_PROBABILITIES"` | `"INVALID_TABLE"` | `"ZERO_VARIANCE"` | `"EMPTY_SAMPLE"` | `"NON_FINITE_SAMPLE"` | `"LENGTH_MISMATCH"` | `"TOO_FEW_CATEGORIES"` | `"SUCCESSES_EXCEED_TRIALS"` | `"INVALID_DEGREES_OF_FREEDOM"` | `"ZERO_TOTAL_COUNT"` | `"INVALID_OPTION"` | `"TOO_SMALL_SAMPLE"` | `"TOO_FEW_GROUPS"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`HypothesisTestInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_COUNT"` | `"INVALID_PROBABILITIES"` | `"INVALID_TABLE"` | `"ZERO_VARIANCE"` | `"EMPTY_SAMPLE"` | `"NON_FINITE_SAMPLE"` | `"LENGTH_MISMATCH"` | `"TOO_FEW_CATEGORIES"` | `"SUCCESSES_EXCEED_TRIALS"` | `"INVALID_DEGREES_OF_FREEDOM"` | `"ZERO_TOTAL_COUNT"` | `"INVALID_OPTION"` | `"TOO_SMALL_SAMPLE"` | `"TOO_FEW_GROUPS"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/hypothesis-test"`
Defined in: [packages/hypothesis-test/src/errors.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L28)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# binomialTest
> **binomialTest**(`successes`, `trials`, `options?`): [`BinomialTestResult`](/reference/knotkit/hypothesis-test/interfaces/binomialtestresult/)
Defined in: [packages/hypothesis-test/src/binomial-test.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L28)
Test the success probability of independent Bernoulli trials. One-sided tails include the observed count. The two-sided test sums all outcomes whose mass is at most that of the observed count, with a relative allowance of 1e-7. Uses O(trials) time and constant working storage.
## Parameters
[Section titled “Parameters”](#parameters)
### successes
[Section titled “successes”](#successes)
`number`
### trials
[Section titled “trials”](#trials)
`number`
### options?
[Section titled “options?”](#options)
[`BinomialTestOptions`](/reference/knotkit/hypothesis-test/interfaces/binomialtestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`BinomialTestResult`](/reference/knotkit/hypothesis-test/interfaces/binomialtestresult/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT`, `SUCCESSES_EXCEED_TRIALS`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` outside the supported binomial parameter domain.
# chiSquaredGoodnessOfFitTest
> **chiSquaredGoodnessOfFitTest**(`observed`, `probabilities`, `options?`): [`ChiSquaredGoodnessOfFitTestResult`](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestresult/)
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L38)
Compare category counts against probabilities scaled by the observed total. The probability sum must lie within 1e-12 of one. The calculation preserves the supplied probabilities. It drops categories with two zero counts and returns a zero p-value when any positive observation has zero expectation.
Pooling works inward from both tails and merges any remaining low interior categories toward larger indices. The p-value is the upper tail of the asymptotic chi-squared distribution. Time and working storage are linear in the category count.
## Parameters
[Section titled “Parameters”](#parameters)
### observed
[Section titled “observed”](#observed)
`ArrayLike`<`number`>
### probabilities
[Section titled “probabilities”](#probabilities)
`ArrayLike`<[`Probability`](/reference/knotkit/distribution/type-aliases/probability/)>
### options?
[Section titled “options?”](#options)
[`ChiSquaredGoodnessOfFitTestOptions`](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`ChiSquaredGoodnessOfFitTestResult`](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestresult/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_COUNT` for an invalid count or unsafe total, `LENGTH_MISMATCH`, `TOO_FEW_CATEGORIES`, `INVALID_PROBABILITIES`, `ZERO_TOTAL_COUNT`, `INVALID_OPTION` for an invalid pooling threshold, or `INVALID_DEGREES_OF_FREEDOM`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` when the degrees of freedom exceed the supported maximum.
# fisherExactTest
> **fisherExactTest**(`table`, `options?`): [`FisherExactTestResult`](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestresult/)
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L40)
Test conditional independence in a 2×2 table with fixed margins. One-sided tails include the observed top-left count, and a zero margin gives a p-value of one. The two-sided test sums all tables whose mass is at most the observed table’s mass, with a relative allowance of 1e-7. Time is linear in the number of tables with the margins supplied. The calculation uses constant working storage.
## Parameters
[Section titled “Parameters”](#parameters)
### table
[Section titled “table”](#table)
[`FisherExactTestTable`](/reference/knotkit/hypothesis-test/type-aliases/fisherexacttesttable/)
### options?
[Section titled “options?”](#options)
[`FisherExactTestOptions`](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`FisherExactTestResult`](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestresult/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_TABLE`, `INVALID_COUNT`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` outside the supported hypergeometric parameter domain.
# kolmogorovSmirnovTest
> **kolmogorovSmirnovTest**(`sample`, `distribution`, `options?`): [`KolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestresult/)
Defined in: [packages/hypothesis-test/src/kolmogorov-smirnov-test.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kolmogorov-smirnov-test.ts#L26)
Compare a finite sample with a specified continuous distribution. The greater alternative uses the maximum of empirical CDF minus reference CDF. The less alternative reverses the subtraction. Two-sided uses the larger of the two distances.
The sample is copied before sorting. Samples with fewer than 100 observations and no repeated values use the exact null distribution. The asymptotic distribution is used for larger samples and for samples with repeated values.
Sorting uses O(n log n) time and O(n) space. The exact two-sided matrix has dimension O(n·statistic) and uses O(log n) matrix products. Other exact tails use O(n) terms.
## Parameters
[Section titled “Parameters”](#parameters)
### sample
[Section titled “sample”](#sample)
`ArrayLike`<`number`>
### distribution
[Section titled “distribution”](#distribution)
[`ContinuousDistribution`](/reference/knotkit/distribution/interfaces/continuousdistribution/)
### options?
[Section titled “options?”](#options)
[`KolmogorovSmirnovTestOptions`](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`KolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `NON_FINITE_SAMPLE`, or `INVALID_OPTION`.
# kruskalWallisTest
> **kruskalWallisTest**(`groups`): [`KruskalWallisTestResult`](/reference/knotkit/hypothesis-test/interfaces/kruskalwallistestresult/)
Defined in: [packages/hypothesis-test/src/kruskal-wallis-test.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kruskal-wallis-test.ts#L27)
Kruskal-Wallis H-test of whether `k >= 2` independent groups come from the same distribution, matching `scipy.stats.kruskal`. The p-value is the upper tail of the chi-squared distribution with `k - 1` degrees of freedom, so there is no `alternative`, and it is an approximation that is unreliable for groups of fewer than about five values. Uses `O(N log N)` time and `O(N)` space for `N` observations.
When every observation is equal the tie correction is zero. SciPy returns NaN there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### groups
[Section titled “groups”](#groups)
`ArrayLike`<`ArrayLike`<`number`>>
## Returns
[Section titled “Returns”](#returns)
[`KruskalWallisTestResult`](/reference/knotkit/hypothesis-test/interfaces/kruskalwallistestresult/)
## Throws
[Section titled “Throws”](#throws)
With `TOO_FEW_GROUPS` below two groups, `EMPTY_SAMPLE`, `NON_FINITE_SAMPLE`, or `ZERO_VARIANCE`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above the supported number of groups.
# mannWhitneyUTest
> **mannWhitneyUTest**(`first`, `second`, `options?`): [`MannWhitneyUTestResult`](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestresult/)
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:100](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L100)
Mann-Whitney U rank test of whether two independent samples come from the same distribution, matching `scipy.stats.mannwhitneyu`. `greater` tests that values of `first` tend to exceed values of `second`. The statistic is the U of `first`.
`auto` uses the exact null distribution when there are no tied values and the smaller sample has at most 8 values, which is SciPy’s rule, provided the distribution costs at most 2e7 steps to build; otherwise it uses the normal approximation with tie correction. `exact` with tied values truncates the statistic as SciPy does. Building the exact distribution takes `O(m² n)` time and `O(m n)` space for sizes `m <= n`.
When every value is equal the variance is zero. SciPy returns NaN there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ArrayLike`<`number`>
### second
[Section titled “second”](#second)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`MannWhitneyUTestOptions`](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`MannWhitneyUTestResult`](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `NON_FINITE_SAMPLE`, `INVALID_OPTION` (also for an `exact` method beyond the work limit), or `ZERO_VARIANCE`.
# oneSampleTTest
> **oneSampleTTest**(`sample`, `expectedMean`, `options?`): [`OneSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/onesamplettestresult/)
Defined in: [packages/hypothesis-test/src/one-sample-t-test.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-sample-t-test.ts#L21)
Student’s t-test of whether a sample’s mean equals `expectedMean`, matching `scipy.stats.ttest_1samp`. The statistic is `(mean - expectedMean) / sqrt(variance / n)` with `n - 1` degrees of freedom. `greater` tests a mean above `expectedMean`. Uses O(n) time and constant working storage.
A constant sample has zero variance. SciPy returns NaN or an infinite statistic there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### sample
[Section titled “sample”](#sample)
`ArrayLike`<`number`>
### expectedMean
[Section titled “expectedMean”](#expectedmean)
`number`
### options?
[Section titled “options?”](#options)
[`OneSampleTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/onesamplettestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`OneSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/onesamplettestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `TOO_SMALL_SAMPLE` below two values, `NON_FINITE_SAMPLE` (also for a non-finite `expectedMean`), `ZERO_VARIANCE`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above 1e5 degrees of freedom.
# oneWayAnova
> **oneWayAnova**(`groups`): [`OneWayAnovaResult`](/reference/knotkit/hypothesis-test/interfaces/onewayanovaresult/)
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L30)
One-way analysis of variance of whether `k >= 2` independent groups share a mean, matching `scipy.stats.f_oneway`. The p-value is the upper tail of the F distribution, so there is no `alternative`. Groups may have different sizes and a group may hold a single value, provided the total exceeds `k`. Uses O(N) time and constant working storage for `N` observations.
When every group is constant, the within-group mean square is zero. SciPy returns NaN or an infinite statistic there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### groups
[Section titled “groups”](#groups)
`ArrayLike`<`ArrayLike`<`number`>>
## Returns
[Section titled “Returns”](#returns)
[`OneWayAnovaResult`](/reference/knotkit/hypothesis-test/interfaces/onewayanovaresult/)
## Throws
[Section titled “Throws”](#throws)
With `TOO_FEW_GROUPS` below two groups, `EMPTY_SAMPLE`, `TOO_SMALL_SAMPLE` when the observations do not exceed the group count, `NON_FINITE_SAMPLE`, or `ZERO_VARIANCE`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above 1e5 degrees of freedom.
# pairedTTest
> **pairedTTest**(`first`, `second`, `options?`): [`PairedTTestResult`](/reference/knotkit/hypothesis-test/interfaces/pairedttestresult/)
Defined in: [packages/hypothesis-test/src/paired-t-test.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/paired-t-test.ts#L21)
Paired-sample t-test of whether the mean of `first[i] - second[i]` is zero, matching `scipy.stats.ttest_rel`. It is `oneSampleTTest` of the differences against zero. `greater` tests a first mean above the second. Uses O(n) time and space.
Constant differences have zero variance. SciPy returns NaN or an infinite statistic there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ArrayLike`<`number`>
### second
[Section titled “second”](#second)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`PairedTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/pairedttestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`PairedTTestResult`](/reference/knotkit/hypothesis-test/interfaces/pairedttestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `LENGTH_MISMATCH`, `TOO_SMALL_SAMPLE` below two pairs, `NON_FINITE_SAMPLE` (also when a difference overflows), `ZERO_VARIANCE`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above 1e5 degrees of freedom.
# twoSampleKolmogorovSmirnovTest
> **twoSampleKolmogorovSmirnovTest**(`first`, `second`, `options?`): [`TwoSampleKolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestresult/)
Defined in: [packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts#L23)
Compare the empirical CDFs of two finite samples. The greater alternative takes the first sample’s CDF minus the second’s. The less alternative reverses the subtraction. Two-sided uses the larger of the two distances.
Both samples are copied before sorting. The exact null distribution is used when the product of the sample sizes is below 10,000 and the pooled sample has no repeated values. The asymptotic distribution is used in other cases.
Sorting and merging take O(m log m + n log n) time and O(m + n) space. The exact null distribution adds O(mn) work.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ArrayLike`<`number`>
### second
[Section titled “second”](#second)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`TwoSampleKolmogorovSmirnovTestOptions`](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`TwoSampleKolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `NON_FINITE_SAMPLE`, or `INVALID_OPTION`.
# twoSampleTTest
> **twoSampleTTest**(`first`, `second`, `options?`): [`TwoSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplettestresult/)
Defined in: [packages/hypothesis-test/src/two-sample-t-test.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-t-test.ts#L23)
Student’s pooled-variance t-test of whether two independent samples share a mean, matching `scipy.stats.ttest_ind(first, second, equal_var=True)`. The statistic is `(mean₁ - mean₂) / se`, where `se` uses the pooled variance, with `m + n - 2` degrees of freedom. `greater` tests a first mean above the second. Use `welchTTest` when the variances may differ. Uses O(m + n) time and constant working storage.
Constant samples have zero pooled variance. SciPy returns NaN or an infinite statistic there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ArrayLike`<`number`>
### second
[Section titled “second”](#second)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`TwoSampleTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/twosamplettestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`TwoSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplettestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `TOO_SMALL_SAMPLE` below three pooled values, `NON_FINITE_SAMPLE`, `ZERO_VARIANCE`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above 1e5 degrees of freedom.
# welchTTest
> **welchTTest**(`first`, `second`, `options?`): [`WelchTTestResult`](/reference/knotkit/hypothesis-test/interfaces/welchttestresult/)
Defined in: [packages/hypothesis-test/src/welch-t-test.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/welch-t-test.ts#L23)
Welch’s unequal-variance t-test of whether two independent samples share a mean, matching `scipy.stats.ttest_ind(first, second, equal_var=False)`. The statistic is `(mean₁ - mean₂) / sqrt(s₁²/m + s₂²/n)`, and the degrees of freedom follow Welch–Satterthwaite, so they are usually fractional. `greater` tests a first mean above the second. Uses O(m + n) time and constant working storage.
Two constant samples have zero standard error. SciPy returns NaN or an infinite statistic there; this function throws. One constant sample alongside a varying one is accepted.
## Parameters
[Section titled “Parameters”](#parameters)
### first
[Section titled “first”](#first)
`ArrayLike`<`number`>
### second
[Section titled “second”](#second)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`WelchTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/welchttestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`WelchTTestResult`](/reference/knotkit/hypothesis-test/interfaces/welchttestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `TOO_SMALL_SAMPLE` below two values in either sample, `NON_FINITE_SAMPLE`, `ZERO_VARIANCE`, or `INVALID_OPTION`.
## Throws
[Section titled “Throws”](#throws-1)
With `INVALID_PARAMETER` above 1e5 degrees of freedom.
# wilcoxonSignedRankTest
> **wilcoxonSignedRankTest**(`differences`, `options?`): [`WilcoxonSignedRankTestResult`](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestresult/)
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L73)
Wilcoxon signed-rank test of whether the distribution of `differences` is symmetric about zero, matching `scipy.stats.wilcoxon` with `zero_method='wilcox'`. For paired samples pass `first[i] - second[i]`; for one sample pass `value - median`. `greater` tests that differences tend to be positive. Zero differences are dropped, and tied absolute values take average ranks.
The exact null distribution is built in `O(n³)` time for `n` nonzero differences, up to 500. With zeros or ties the exact p-value rounds the statistic conservatively, as SciPy does. The normal approximation applies the tie correction.
When every difference is zero nothing is ranked. SciPy returns NaN there; this function throws.
## Parameters
[Section titled “Parameters”](#parameters)
### differences
[Section titled “differences”](#differences)
`ArrayLike`<`number`>
### options?
[Section titled “options?”](#options)
[`WilcoxonSignedRankTestOptions`](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestoptions/)
## Returns
[Section titled “Returns”](#returns)
[`WilcoxonSignedRankTestResult`](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestresult/)
## Throws
[Section titled “Throws”](#throws)
With `EMPTY_SAMPLE`, `NON_FINITE_SAMPLE`, `INVALID_OPTION` (also for an `exact` method above 500 nonzero differences), or `ZERO_VARIANCE` when every difference is zero.
# AlternativeHypothesisTestResult
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L27)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BinomialTestResult`](/reference/knotkit/hypothesis-test/interfaces/binomialtestresult/)
* [`FisherExactTestResult`](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestresult/)
* [`KolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestresult/)
* [`TwoSampleKolmogorovSmirnovTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestresult/)
* [`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
* [`MannWhitneyUTestResult`](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestresult/)
* [`WilcoxonSignedRankTestResult`](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestresult/)
## Properties
[Section titled “Properties”](#properties)
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L21)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#statistic)
***
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#pvalue)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#method)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
# BinomialTestOptions
Defined in: [packages/hypothesis-test/src/binomial-test.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L9)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### successProbability?
[Section titled “successProbability?”](#successprobability)
> `readonly` `optional` **successProbability?**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/binomial-test.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L11)
Common success probability under the null. Defaults to one half.
***
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# BinomialTestResult
Defined in: [packages/hypothesis-test/src/binomial-test.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L14)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/binomial-test.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L16)
Observed number of successes.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/binomial-test.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/binomial-test.ts#L17)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
# ChiSquaredGoodnessOfFitTestOptions
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L7)
## Properties
[Section titled “Properties”](#properties)
### estimatedParameterCount?
[Section titled “estimatedParameterCount?”](#estimatedparametercount)
> `readonly` `optional` **estimatedParameterCount?**: `number`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L9)
Number of fitted parameters deducted from the degrees of freedom. Defaults to zero.
***
### minimumExpectedCount?
[Section titled “minimumExpectedCount?”](#minimumexpectedcount)
> `readonly` `optional` **minimumExpectedCount?**: `number`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L11)
Pool adjacent categories to reach this expected count. Zero disables pooling.
# ChiSquaredGoodnessOfFitTestResult
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L14)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L16)
Sum of squared observed-minus-expected count differences divided by the respective expectations.
#### Overrides
[Section titled “Overrides”](#overrides)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#statistic)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"asymptotic"`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L17)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#method)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L19)
Retained categories minus one minus the fitted parameter count.
***
### smallestExpectedCount
[Section titled “smallestExpectedCount”](#smallestexpectedcount)
> `readonly` **smallestExpectedCount**: `number`
Defined in: [packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/chi-squared-goodness-of-fit-test.ts#L21)
Smallest expected count among retained categories after any pooling.
***
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#pvalue)
# FisherExactTestOptions
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L10)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# FisherExactTestResult
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L12)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L14)
Observed count in the top-left cell.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L15)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
# HypothesisTestAlternativeOptions
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L15)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BinomialTestOptions`](/reference/knotkit/hypothesis-test/interfaces/binomialtestoptions/)
* [`FisherExactTestOptions`](/reference/knotkit/hypothesis-test/interfaces/fisherexacttestoptions/)
* [`KolmogorovSmirnovTestOptions`](/reference/knotkit/hypothesis-test/interfaces/kolmogorovsmirnovtestoptions/)
* [`TwoSampleKolmogorovSmirnovTestOptions`](/reference/knotkit/hypothesis-test/interfaces/twosamplekolmogorovsmirnovtestoptions/)
* [`OneSampleTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/onesamplettestoptions/)
* [`PairedTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/pairedttestoptions/)
* [`TwoSampleTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/twosamplettestoptions/)
* [`WelchTTestOptions`](/reference/knotkit/hypothesis-test/interfaces/welchttestoptions/)
* [`MannWhitneyUTestOptions`](/reference/knotkit/hypothesis-test/interfaces/mannwhitneyutestoptions/)
* [`WilcoxonSignedRankTestOptions`](/reference/knotkit/hypothesis-test/interfaces/wilcoxonsignedranktestoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
# HypothesisTestResult
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L20)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`ChiSquaredGoodnessOfFitTestResult`](/reference/knotkit/hypothesis-test/interfaces/chisquaredgoodnessoffittestresult/)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
* [`KruskalWallisTestResult`](/reference/knotkit/hypothesis-test/interfaces/kruskalwallistestresult/)
* [`OneWayAnovaResult`](/reference/knotkit/hypothesis-test/interfaces/onewayanovaresult/)
## Properties
[Section titled “Properties”](#properties)
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L21)
***
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
# KolmogorovSmirnovTestOptions
Defined in: [packages/hypothesis-test/src/kolmogorov-smirnov-test.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kolmogorov-smirnov-test.ts#L6)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# KolmogorovSmirnovTestResult
Defined in: [packages/hypothesis-test/src/kolmogorov-smirnov-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kolmogorov-smirnov-test.ts#L8)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/kolmogorov-smirnov-test.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kolmogorov-smirnov-test.ts#L10)
Maximum distance between the empirical CDF and the supplied CDF in the selected direction.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
# KruskalWallisTestResult
Defined in: [packages/hypothesis-test/src/kruskal-wallis-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kruskal-wallis-test.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#pvalue)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/kruskal-wallis-test.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kruskal-wallis-test.ts#L9)
The tie-corrected H statistic.
#### Overrides
[Section titled “Overrides”](#overrides)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/kruskal-wallis-test.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kruskal-wallis-test.ts#L11)
The number of groups minus one.
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"asymptotic"`
Defined in: [packages/hypothesis-test/src/kruskal-wallis-test.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/kruskal-wallis-test.ts#L12)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#method)
# MannWhitneyUTestOptions
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L11)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
***
### method?
[Section titled “method?”](#method)
> `readonly` `optional` **method?**: [`HypothesisTestMethodOption`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethodoption/)
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L13)
Defaults to `auto`: `exact` without tied values when the smaller sample has at most 8 values, else `asymptotic`.
***
### continuityCorrection?
[Section titled “continuityCorrection?”](#continuitycorrection)
> `readonly` `optional` **continuityCorrection?**: `boolean`
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L15)
Subtract one half from the normal approximation. Defaults to `true`. The exact method ignores it.
# MannWhitneyUTestResult
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L18)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L20)
The U statistic of `first`: the number of pairs where `first` exceeds `second`, counting ties as one half.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
***
### secondStatistic
[Section titled “secondStatistic”](#secondstatistic)
> `readonly` **secondStatistic**: `number`
Defined in: [packages/hypothesis-test/src/mann-whitney-u-test.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/mann-whitney-u-test.ts#L22)
The U statistic of `second`, which is `first.length * second.length - statistic`.
# OneSampleTTestOptions
Defined in: [packages/hypothesis-test/src/one-sample-t-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-sample-t-test.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# OneSampleTTestResult
Defined in: [packages/hypothesis-test/src/one-sample-t-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-sample-t-test.ts#L8)
## Extends
[Section titled “Extends”](#extends)
* [`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L5)
Student’s t statistic. Positive when the sample mean, or first mean, exceeds the reference.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L7)
Degrees of freedom of the null t distribution. Welch’s test reports a fractional value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`degreesOfFreedom`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#degreesoffreedom)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L8)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#method)
# OneWayAnovaResult
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#pvalue)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L9)
The F statistic, the between-group mean square over the within-group mean square.
#### Overrides
[Section titled “Overrides”](#overrides)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#statistic)
***
### numeratorDegreesOfFreedom
[Section titled “numeratorDegreesOfFreedom”](#numeratordegreesoffreedom)
> `readonly` **numeratorDegreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L11)
The number of groups minus one.
***
### denominatorDegreesOfFreedom
[Section titled “denominatorDegreesOfFreedom”](#denominatordegreesoffreedom)
> `readonly` **denominatorDegreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L13)
The number of observations minus the number of groups.
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/one-way-anova.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/one-way-anova.ts#L14)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`HypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestresult/#method)
# PairedTTestOptions
Defined in: [packages/hypothesis-test/src/paired-t-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/paired-t-test.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# PairedTTestResult
Defined in: [packages/hypothesis-test/src/paired-t-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/paired-t-test.ts#L8)
## Extends
[Section titled “Extends”](#extends)
* [`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L5)
Student’s t statistic. Positive when the sample mean, or first mean, exceeds the reference.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L7)
Degrees of freedom of the null t distribution. Welch’s test reports a fractional value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`degreesOfFreedom`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#degreesoffreedom)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L8)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#method)
# TTestResult
Defined in: [packages/hypothesis-test/src/t-test-result.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L3)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Extended by
[Section titled “Extended by”](#extended-by)
* [`OneSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/onesamplettestresult/)
* [`PairedTTestResult`](/reference/knotkit/hypothesis-test/interfaces/pairedttestresult/)
* [`TwoSampleTTestResult`](/reference/knotkit/hypothesis-test/interfaces/twosamplettestresult/)
* [`WelchTTestResult`](/reference/knotkit/hypothesis-test/interfaces/welchttestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L5)
Student’s t statistic. Positive when the sample mean, or first mean, exceeds the reference.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L7)
Degrees of freedom of the null t distribution. Welch’s test reports a fractional value.
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L8)
#### Overrides
[Section titled “Overrides”](#overrides-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
# TwoSampleKolmogorovSmirnovTestOptions
Defined in: [packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts#L5)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# TwoSampleKolmogorovSmirnovTestResult
Defined in: [packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-kolmogorov-smirnov-test.ts#L9)
Maximum distance between the two empirical CDFs in the selected direction.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
# TwoSampleTTestOptions
Defined in: [packages/hypothesis-test/src/two-sample-t-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-t-test.ts#L8)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# TwoSampleTTestResult
Defined in: [packages/hypothesis-test/src/two-sample-t-test.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/two-sample-t-test.ts#L9)
## Extends
[Section titled “Extends”](#extends)
* [`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L5)
Student’s t statistic. Positive when the sample mean, or first mean, exceeds the reference.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L7)
Degrees of freedom of the null t distribution. Welch’s test reports a fractional value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`degreesOfFreedom`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#degreesoffreedom)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L8)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#method)
# WelchTTestOptions
Defined in: [packages/hypothesis-test/src/welch-t-test.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/welch-t-test.ts#L7)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
# WelchTTestResult
Defined in: [packages/hypothesis-test/src/welch-t-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/welch-t-test.ts#L8)
## Extends
[Section titled “Extends”](#extends)
* [`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#pvalue)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L5)
Student’s t statistic. Positive when the sample mean, or first mean, exceeds the reference.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#statistic)
***
### degreesOfFreedom
[Section titled “degreesOfFreedom”](#degreesoffreedom)
> `readonly` **degreesOfFreedom**: `number`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L7)
Degrees of freedom of the null t distribution. Welch’s test reports a fractional value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`degreesOfFreedom`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#degreesoffreedom)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: `"exact"`
Defined in: [packages/hypothesis-test/src/t-test-result.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/t-test-result.ts#L8)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`TTestResult`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/ttestresult/#method)
# WilcoxonSignedRankTestOptions
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L12)
## Extends
[Section titled “Extends”](#extends)
* [`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/)
## Properties
[Section titled “Properties”](#properties)
### alternative?
[Section titled “alternative?”](#alternative)
> `readonly` `optional` **alternative?**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L17)
Defaults to `two-sided`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HypothesisTestAlternativeOptions`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/hypothesistestalternativeoptions/#alternative)
***
### method?
[Section titled “method?”](#method)
> `readonly` `optional` **method?**: [`HypothesisTestMethodOption`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethodoption/)
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L17)
Defaults to `auto`: `exact` without zero or tied differences up to 50 differences, else `asymptotic`. SciPy’s `auto` runs a permutation test for tied or zero differences up to 13 values; this function uses `asymptotic`.
***
### continuityCorrection?
[Section titled “continuityCorrection?”](#continuitycorrection)
> `readonly` `optional` **continuityCorrection?**: `boolean`
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L19)
Move the normal approximation half a rank toward the mean. Defaults to `false`, as in SciPy.
# WilcoxonSignedRankTestResult
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L22)
## Extends
[Section titled “Extends”](#extends)
* [`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/)
## Properties
[Section titled “Properties”](#properties)
### pValue
[Section titled “pValue”](#pvalue)
> `readonly` **pValue**: [`Probability`](/reference/knotkit/distribution/type-aliases/probability/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L23)
Null probability of a result at least as extreme as the observed one.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`pValue`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#pvalue)
***
### method
[Section titled “method”](#method)
> `readonly` **method**: [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L24)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`method`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#method)
***
### alternative
[Section titled “alternative”](#alternative)
> `readonly` **alternative**: `"two-sided"` | `"less"` | `"greater"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L29)
The alternative hypothesis used to order outcomes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`alternative`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#alternative)
***
### statistic
[Section titled “statistic”](#statistic)
> `readonly` **statistic**: `number`
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L24)
The smaller of the positive and negative rank sums for `two-sided`, else the positive rank sum.
#### Overrides
[Section titled “Overrides”](#overrides)
[`AlternativeHypothesisTestResult`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/).[`statistic`](/reference/knotkit/hypothesis-test/interfaces/alternativehypothesistestresult/#statistic)
***
### nonzeroCount
[Section titled “nonzeroCount”](#nonzerocount)
> `readonly` **nonzeroCount**: `number`
Defined in: [packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/wilcoxon-signed-rank-test.ts#L26)
The number of nonzero differences ranked.
# FisherExactTestTable
> **FisherExactTestTable** = readonly \[readonly \[`number`, `number`], readonly \[`number`, `number`]]
Defined in: [packages/hypothesis-test/src/fisher-exact-test.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/fisher-exact-test.ts#L8)
A 2×2 table of observed counts, in row order.
# HypothesisTestAlternative
> **HypothesisTestAlternative** = *typeof* [`HYPOTHESIS_TEST_ALTERNATIVES`](/reference/knotkit/hypothesis-test/variables/hypothesis_test_alternatives/)\[`number`]
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L10)
Direction of the alternative hypothesis.
# HypothesisTestErrorCode
> **HypothesisTestErrorCode** = [`HypothesisTestInvalidInputErrorCode`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestinvalidinputerrorcode/)
Defined in: [packages/hypothesis-test/src/errors.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L24)
# HypothesisTestInvalidInputErrorCode
> **HypothesisTestInvalidInputErrorCode** = *typeof* [`HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/hypothesis-test/variables/hypothesis_test_invalid_input_error_codes/)\[`number`]
Defined in: [packages/hypothesis-test/src/errors.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L23)
# HypothesisTestMethod
> **HypothesisTestMethod** = `"exact"` | `"asymptotic"`
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L13)
Whether the p-value uses a finite-sample null distribution or its large-sample approximation.
# HypothesisTestMethodOption
> **HypothesisTestMethodOption** = `"auto"` | [`HypothesisTestMethod`](/reference/knotkit/hypothesis-test/type-aliases/hypothesistestmethod/)
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L33)
The p-value method a rank test may be asked for. `auto` picks `exact` or `asymptotic` from the input.
# HYPOTHESIS_TEST_ALTERNATIVES
> `const` **HYPOTHESIS_TEST_ALTERNATIVES**: readonly \[`"two-sided"`, `"less"`, `"greater"`]
Defined in: [packages/hypothesis-test/src/hypothesis-test-result.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/hypothesis-test-result.ts#L3)
# HYPOTHESIS_TEST_ERROR_CODES
> `const` **HYPOTHESIS_TEST_ERROR_CODES**: *typeof* [`HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/hypothesis-test/variables/hypothesis_test_invalid_input_error_codes/) = `HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/hypothesis-test/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L20)
# HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES
> `const` **HYPOTHESIS_TEST_INVALID_INPUT_ERROR_CODES**: readonly \[`"EMPTY_SAMPLE"`, `"NON_FINITE_SAMPLE"`, `"INVALID_COUNT"`, `"INVALID_PROBABILITIES"`, `"LENGTH_MISMATCH"`, `"TOO_FEW_CATEGORIES"`, `"INVALID_TABLE"`, `"SUCCESSES_EXCEED_TRIALS"`, `"INVALID_DEGREES_OF_FREEDOM"`, `"ZERO_TOTAL_COUNT"`, `"INVALID_OPTION"`, `"TOO_SMALL_SAMPLE"`, `"TOO_FEW_GROUPS"`, `"ZERO_VARIANCE"`]
Defined in: [packages/hypothesis-test/src/errors.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/hypothesis-test/src/errors.ts#L3)
# knotkit/interval-index
## Classes
[Section titled “Classes”](#classes)
* [IntervalIndexInvalidInputError](/reference/knotkit/interval-index/classes/intervalindexinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [IntervalEntry](/reference/knotkit/interval-index/interfaces/intervalentry/)
* [IntervalIndex](/reference/knotkit/interval-index/interfaces/intervalindex/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [IntervalIndexInvalidInputErrorCode](/reference/knotkit/interval-index/type-aliases/intervalindexinvalidinputerrorcode/)
* [IntervalIndexErrorCode](/reference/knotkit/interval-index/type-aliases/intervalindexerrorcode/)
* [IntervalIndexKind](/reference/knotkit/interval-index/type-aliases/intervalindexkind/)
* [IntervalInput](/reference/knotkit/interval-index/type-aliases/intervalinput/)
* [IntervalIndexFactory](/reference/knotkit/interval-index/type-aliases/intervalindexfactory/)
## Variables
[Section titled “Variables”](#variables)
* [INTERVAL_INDEX_INVALID_INPUT_ERROR_CODES](/reference/knotkit/interval-index/variables/interval_index_invalid_input_error_codes/)
* [INTERVAL_INDEX_ERROR_CODES](/reference/knotkit/interval-index/variables/interval_index_error_codes/)
* [INTERVAL_INDEX_KINDS](/reference/knotkit/interval-index/variables/interval_index_kinds/)
* [\_\_INTERVAL_INDEX_LAYOUTS](/reference/knotkit/interval-index/variables/interval_index_layouts/)
## Functions
[Section titled “Functions”](#functions)
* [augmentedRedBlackIntervalIndex](/reference/knotkit/interval-index/functions/augmentedredblackintervalindex/)
* [sortedArrayIntervalIndex](/reference/knotkit/interval-index/functions/sortedarrayintervalindex/)
# IntervalIndexInvalidInputError
Defined in: [packages/interval-index/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L21)
Thrown when an interval or a query range has a start that sorts after its end, or when an iterator advances after the index it walks changed.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`IntervalIndexInvalidInputErrorCode`](/reference/knotkit/interval-index/type-aliases/intervalindexinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new IntervalIndexInvalidInputError**(`code`, `message`): `IntervalIndexInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"MODIFIED_DURING_ITERATION"` | `"INVALID_INTERVAL"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`IntervalIndexInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"MODIFIED_DURING_ITERATION"` | `"INVALID_INTERVAL"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/interval-index"`
Defined in: [packages/interval-index/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L22)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# augmentedRedBlackIntervalIndex
> **augmentedRedBlackIntervalIndex**<`K`, `V`>(`order`, `initialEntries?`): [`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
Defined in: [packages/interval-index/src/augmented-red-black-interval-index.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/augmented-red-black-interval-index.ts#L17)
Create an interval index backed by a red-black tree keyed by `(start, id)`, each node augmented with the largest `end` in its subtree, plus a map from id to node.
`add` and `delete` take O(log n) time and `has` and `get` O(1). `atPoint` and `overlapping` reporting k entries take O(min(n, (k + 1) log n)) time: a subtree is skipped when its largest end sorts before the query start, and the walk stops at the first start past the query end. A full walk takes O(n). Space is O(n).
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### initialEntries?
[Section titled “initialEntries?”](#initialentries)
`Iterable`<[`IntervalInput`](/reference/knotkit/interval-index/type-aliases/intervalinput/)<`K`, `V`>, `any`, `any`>
## Returns
[Section titled “Returns”](#returns)
[`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_INTERVAL` when an initial entry’s start sorts after its end.
## See
[Section titled “See”](#see)
Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, 3rd ed., section 14.3, “Interval trees”.
# sortedArrayIntervalIndex
> **sortedArrayIntervalIndex**<`K`, `V`>(`order`, `initialEntries?`): [`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
Defined in: [packages/interval-index/src/sorted-array-interval-index.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/sorted-array-interval-index.ts#L37)
Create an interval index backed by one array of entries sorted by `(start, id)` and a parallel array whose i-th key is the largest `end` among the first i + 1 entries, plus a map from id to entry.
Construction from n initial entries takes O(n log n) time. An `add` whose start sorts at or after the last stored start appends in O(1) amortized time; any other `add` takes O(1). A successful `delete` takes amortized O(1), compacting in O(n) when half the entries have been deleted. Both operations leave the query index to be rebuilt by the next query or walk, in O(n log n) after an out-of-order `add` and O(n) after deletions alone. `has` and `get` take O(1). A settled `atPoint` or `overlapping` takes O(log n + m) time, where m counts the entries between the first one whose running maximum end reaches the query start and the last one starting at or before the query end; m is at least the k entries reported and at most n. A full walk takes O(n). Space is O(n).
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### initialEntries?
[Section titled “initialEntries?”](#initialentries)
`Iterable`<[`IntervalInput`](/reference/knotkit/interval-index/type-aliases/intervalinput/)<`K`, `V`>, `any`, `any`>
## Returns
[Section titled “Returns”](#returns)
[`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_INTERVAL` when an initial entry’s start sorts after its end.
# IntervalEntry
Defined in: [packages/interval-index/src/interval-index.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L19)
One stored closed interval `[start, end]` and its value. `id` is the number `add` returned for it. An entry is frozen: the index hands out the object it stores, so a caller cannot move an interval without `delete` and `add`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### id
[Section titled “id”](#id)
> `readonly` **id**: `number`
Defined in: [packages/interval-index/src/interval-index.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L20)
***
### start
[Section titled “start”](#start)
> `readonly` **start**: `K`
Defined in: [packages/interval-index/src/interval-index.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L21)
***
### end
[Section titled “end”](#end)
> `readonly` **end**: `K`
Defined in: [packages/interval-index/src/interval-index.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L22)
***
### value
[Section titled “value”](#value)
> `readonly` **value**: `V`
Defined in: [packages/interval-index/src/interval-index.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L23)
# IntervalIndex
Defined in: [packages/interval-index/src/interval-index.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L37)
A mutable set of closed intervals `[start, end]` over an injected `Order`, answering which intervals hold a point or overlap a range.
Entries are identified by the `id` that `add` returns, so identical intervals coexist. Every walk yields entries in ascending `(start, id)` order. Keep the order a stable total order, keep stored keys unchanged, and keep the order free of writes to the index.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"augmented-red-black-tree"` | `"sorted-array"`
Defined in: [packages/interval-index/src/interval-index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L38)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/interval-index/src/interval-index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L40)
Number of stored entries.
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`start`, `end`, `value`) => `number`
Defined in: [packages/interval-index/src/interval-index.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L47)
Store the closed interval `[start, end]` and return its id: a nonnegative integer, larger than every id this index returned before, never reused, including after `clear`. Initial entries take ids `0, 1, …` in input order.
#### Parameters
[Section titled “Parameters”](#parameters)
##### start
[Section titled “start”](#start)
`K`
##### end
[Section titled “end”](#end)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns)
`number`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_INTERVAL` when `start` sorts after `end`.
***
### delete
[Section titled “delete”](#delete)
> `readonly` **delete**: (`id`) => `boolean`
Defined in: [packages/interval-index/src/interval-index.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L49)
Remove the entry with `id` and report whether it existed.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### id
[Section titled “id”](#id)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`id`) => `boolean`
Defined in: [packages/interval-index/src/interval-index.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L51)
Whether an entry with `id` is stored. O(1).
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### id
[Section titled “id”](#id-1)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`id`) => [`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`> | `undefined`
Defined in: [packages/interval-index/src/interval-index.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L53)
The stored entry with `id`, or `undefined`. O(1).
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### id
[Section titled “id”](#id-2)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`> | `undefined`
***
### atPoint
[Section titled “atPoint”](#atpoint)
> `readonly` **atPoint**: (`point`) => `IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
Defined in: [packages/interval-index/src/interval-index.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L60)
Walk every entry whose interval holds `point`: `start <= point <= end` under the order.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### point
[Section titled “point”](#point)
`K`
#### Returns
[Section titled “Returns”](#returns-4)
`IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
#### Throws
[Section titled “Throws”](#throws-1)
With `MODIFIED_DURING_ITERATION` on advancement after an `add`, a successful `delete`, or a `clear` of a nonempty index.
***
### overlapping
[Section titled “overlapping”](#overlapping)
> `readonly` **overlapping**: (`start`, `end`) => `IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
Defined in: [packages/interval-index/src/interval-index.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L69)
Walk every entry whose interval shares at least one point with the closed range `[start, end]`: `entry.start <= end` and `start <= entry.end`. Touching endpoints overlap. The range is checked when the call is made, not on the first step.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### start
[Section titled “start”](#start-1)
`K`
##### end
[Section titled “end”](#end-1)
`K`
#### Returns
[Section titled “Returns”](#returns-5)
`IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_INTERVAL` when `start` sorts after `end`, or `MODIFIED_DURING_ITERATION` on advancement after an `add`, a successful `delete`, or a `clear` of a nonempty index.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
Defined in: [packages/interval-index/src/interval-index.ts:76](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L76)
Walk every entry in ascending `(start, id)` order.
#### Returns
[Section titled “Returns”](#returns-6)
`IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
#### Throws
[Section titled “Throws”](#throws-3)
With `MODIFIED_DURING_ITERATION` on advancement after an `add`, a successful `delete`, or a `clear` of a nonempty index.
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
Defined in: [packages/interval-index/src/interval-index.ts:83](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L83)
The same function as `entries`.
#### Returns
[Section titled “Returns”](#returns-7)
`IterableIterator`<[`IntervalEntry`](/reference/knotkit/interval-index/interfaces/intervalentry/)<`K`, `V`>>
#### Throws
[Section titled “Throws”](#throws-4)
With `MODIFIED_DURING_ITERATION` on advancement after an `add`, a successful `delete`, or a `clear` of a nonempty index.
***
### clear
[Section titled “clear”](#clear)
> `readonly` **clear**: () => `void`
Defined in: [packages/interval-index/src/interval-index.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L85)
Remove every entry. Ids keep counting up from where they were.
#### Returns
[Section titled “Returns”](#returns-8)
`void`
# IntervalIndexErrorCode
> **IntervalIndexErrorCode** = [`IntervalIndexInvalidInputErrorCode`](/reference/knotkit/interval-index/type-aliases/intervalindexinvalidinputerrorcode/)
Defined in: [packages/interval-index/src/errors.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L10)
A machine-readable error code emitted by `knotkit/interval-index`.
# IntervalIndexFactory
> **IntervalIndexFactory** = <`K`, `V`>(`order`, `initialEntries?`) => [`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
Defined in: [packages/interval-index/src/interval-index.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L93)
A factory that builds an [IntervalIndex](/reference/knotkit/interval-index/interfaces/intervalindex/) over `order`, optionally seeded with initial entries.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### initialEntries?
[Section titled “initialEntries?”](#initialentries)
`Iterable`<[`IntervalInput`](/reference/knotkit/interval-index/type-aliases/intervalinput/)<`K`, `V`>>
## Returns
[Section titled “Returns”](#returns)
[`IntervalIndex`](/reference/knotkit/interval-index/interfaces/intervalindex/)<`K`, `V`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_INTERVAL` when an initial entry’s start sorts after its end.
# IntervalIndexInvalidInputErrorCode
> **IntervalIndexInvalidInputErrorCode** = *typeof* [`INTERVAL_INDEX_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/interval-index/variables/interval_index_invalid_input_error_codes/)\[`number`]
Defined in: [packages/interval-index/src/errors.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L7)
A machine-readable invalid-input code emitted by `knotkit/interval-index`.
# IntervalIndexKind
> **IntervalIndexKind** = *typeof* [`INTERVAL_INDEX_KINDS`](/reference/knotkit/interval-index/variables/interval_index_kinds/)\[`number`]
Defined in: [packages/interval-index/src/interval-index.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L13)
A layout of [IntervalIndex](/reference/knotkit/interval-index/interfaces/intervalindex/), the serializable discriminant its `kind` reports.
# IntervalInput
> **IntervalInput**<`K`, `V`> = readonly \[`start`: `K`, `end`: `K`, `value`: `V`]
Defined in: [packages/interval-index/src/interval-index.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L27)
One interval for a factory’s initial entries, in the same argument order as `add`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
# INTERVAL_INDEX_ERROR_CODES
> `const` **INTERVAL_INDEX_ERROR_CODES**: readonly [`IntervalIndexErrorCode`](/reference/knotkit/interval-index/type-aliases/intervalindexerrorcode/)\[]
Defined in: [packages/interval-index/src/errors.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L13)
Every code emitted by `knotkit/interval-index`, derived from the invalid-input list.
# INTERVAL_INDEX_INVALID_INPUT_ERROR_CODES
> `const` **INTERVAL_INDEX_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_INTERVAL"`, `"MODIFIED_DURING_ITERATION"`]
Defined in: [packages/interval-index/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/interval-index`.
# INTERVAL_INDEX_KINDS
> `const` **INTERVAL_INDEX_KINDS**: readonly \[`"augmented-red-black-tree"`, `"sorted-array"`]
Defined in: [packages/interval-index/src/interval-index.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/interval-index.ts#L7)
The index layouts this package constructs, in recommended-default order. `augmented-red-black-tree` keeps every update logarithmic; `sorted-array` keeps entries contiguous for a set that is built once and queried many times.
# __INTERVAL_INDEX_LAYOUTS
> `const` **\_\_INTERVAL_INDEX_LAYOUTS**: `Readonly`<`Record`<[`IntervalIndexKind`](/reference/knotkit/interval-index/type-aliases/intervalindexkind/), [`IntervalIndexFactory`](/reference/knotkit/interval-index/type-aliases/intervalindexfactory/)>>
Defined in: [packages/interval-index/src/layouts.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/interval-index/src/layouts.ts#L11)
Every interval index layout this package constructs, keyed by the `kind` it reports.
Exported so a property test, a benchmark, or a `problems/*` preset can sweep every layout without naming one. A caller building one index imports `augmentedRedBlackIntervalIndex` or `sortedArrayIntervalIndex` directly.
# knotkit/inverted-index
## Classes
[Section titled “Classes”](#classes)
* [InvertedIndexInvalidInputError](/reference/knotkit/inverted-index/classes/invertedindexinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [InvertedIndex](/reference/knotkit/inverted-index/interfaces/invertedindex/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [InvertedIndexInvalidInputErrorCode](/reference/knotkit/inverted-index/type-aliases/invertedindexinvalidinputerrorcode/)
* [InvertedIndexErrorCode](/reference/knotkit/inverted-index/type-aliases/invertedindexerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [INVERTED_INDEX_INVALID_INPUT_ERROR_CODES](/reference/knotkit/inverted-index/variables/inverted_index_invalid_input_error_codes/)
* [INVERTED_INDEX_ERROR_CODES](/reference/knotkit/inverted-index/variables/inverted_index_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [invertedIndex](/reference/knotkit/inverted-index/functions/invertedindex/)
# InvertedIndexInvalidInputError
Defined in: [packages/inverted-index/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L21)
Building the index exceeded the packed representation or the runtime’s storage capacity.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`InvertedIndexInvalidInputErrorCode`](/reference/knotkit/inverted-index/type-aliases/invertedindexinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new InvertedIndexInvalidInputError**(`code`, `message`): `InvertedIndexInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"MAX_CAPACITY_EXCEEDED"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`InvertedIndexInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"MAX_CAPACITY_EXCEEDED"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/inverted-index"`
Defined in: [packages/inverted-index/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L22)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# invertedIndex
> **invertedIndex**<`R`, `K`>(`records`, `keysOf`): [`InvertedIndex`](/reference/knotkit/inverted-index/interfaces/invertedindex/)<`K`>
Defined in: [packages/inverted-index/src/inverted-index.ts:187](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L187)
Index `records` by the exact keys returned by `keysOf(record, id)`. The selector is called once per record. Each iterable is consumed once. Keys use Map equality. Repeated keys on one record yield one posting. IDs denote positions in the input at build time. The index retains keys and IDs after construction.
Expected O(n + t) construction time for n records and t yielded keys, excluding the selector’s own work. With p distinct record/key associations and k distinct keys, both build workspace and retained storage are O(p + k). A single-key lookup costs expected O(1) plus O(1) per returned ID.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### R
[Section titled “R”](#r)
`R`
### K
[Section titled “K”](#k)
`K`
## Parameters
[Section titled “Parameters”](#parameters)
### records
[Section titled “records”](#records)
`Iterable`<`R`>
### keysOf
[Section titled “keysOf”](#keysof)
(`record`, `id`) => `Iterable`<`K`>
## Returns
[Section titled “Returns”](#returns)
[`InvertedIndex`](/reference/knotkit/inverted-index/interfaces/invertedindex/)<`K`>
## Throws
[Section titled “Throws”](#throws)
With code `MAX_CAPACITY_EXCEEDED` when a record ID or the posting count exceeds 2³² − 1, or when the runtime rejects the key table or packed columns. Errors raised by input iterators and the selector propagate to the caller.
# InvertedIndex
Defined in: [packages/inverted-index/src/inverted-index.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L5)
Immutable association from exact keys to the zero-based IDs of records that contained them.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/inverted-index/src/inverted-index.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L7)
Number of distinct keys. O(1).
***
### recordCount
[Section titled “recordCount”](#recordcount)
> `readonly` **recordCount**: `number`
Defined in: [packages/inverted-index/src/inverted-index.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L9)
Number of input records, including records with no keys. O(1).
***
### postings
[Section titled “postings”](#postings)
> `readonly` **postings**: (`key`) => `IterableIterator`<`number`>
Defined in: [packages/inverted-index/src/inverted-index.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L11)
A fresh iterator of matching record IDs, ascending and unique. A missing key yields an empty iterator.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
#### Returns
[Section titled “Returns”](#returns)
`IterableIterator`<`number`>
***
### keys
[Section titled “keys”](#keys)
> `readonly` **keys**: () => `IterableIterator`<`K`>
Defined in: [packages/inverted-index/src/inverted-index.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L13)
A fresh iterator of keys in first-seen order.
#### Returns
[Section titled “Returns”](#returns-1)
`IterableIterator`<`K`>
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: () => `IterableIterator`\]>
Defined in: [packages/inverted-index/src/inverted-index.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L15)
A fresh iterator of keys paired with independent posting iterators, in first-seen key order.
#### Returns
[Section titled “Returns”](#returns-2)
`IterableIterator`\]>
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\]>
Defined in: [packages/inverted-index/src/inverted-index.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L17)
The same function as `entries`.
#### Returns
[Section titled “Returns”](#returns-3)
`IterableIterator`\]>
***
### forEachAny
[Section titled “forEachAny”](#foreachany)
> `readonly` **forEachAny**: (`keys`, `visit`) => `void`
Defined in: [packages/inverted-index/src/inverted-index.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/inverted-index.ts#L23)
Visit each record matching any query key once, in ascending order. An empty query visits nothing. With k query keys and u matching records, uses O(k) temporary space and O(k × (u + 1)) time. Each call owns its cursors. The visitor can query the index recursively. Visitor and iterable errors propagate.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### keys
[Section titled “keys”](#keys-1)
`Iterable`<`K`>
##### visit
[Section titled “visit”](#visit)
(`id`) => `void`
#### Returns
[Section titled “Returns”](#returns-4)
`void`
# InvertedIndexErrorCode
> **InvertedIndexErrorCode** = *typeof* [`INVERTED_INDEX_ERROR_CODES`](/reference/knotkit/inverted-index/variables/inverted_index_error_codes/)\[`number`]
Defined in: [packages/inverted-index/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L18)
A machine-readable error code emitted by `knotkit/inverted-index`.
# InvertedIndexInvalidInputErrorCode
> **InvertedIndexInvalidInputErrorCode** = *typeof* `invalidInputCodes`\[`number`]
Defined in: [packages/inverted-index/src/errors.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L10)
A machine-readable input error emitted by `knotkit/inverted-index`.
# INVERTED_INDEX_ERROR_CODES
> `const` **INVERTED_INDEX_ERROR_CODES**: readonly [`InvertedIndexInvalidInputErrorCode`](/reference/knotkit/inverted-index/type-aliases/invertedindexinvalidinputerrorcode/)\[]
Defined in: [packages/inverted-index/src/errors.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L13)
All error codes emitted by `knotkit/inverted-index`.
# INVERTED_INDEX_INVALID_INPUT_ERROR_CODES
> `const` **INVERTED_INDEX_INVALID_INPUT_ERROR_CODES**: `Readonly`<*typeof* `invalidInputCodes`>
Defined in: [packages/inverted-index/src/errors.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/inverted-index/src/errors.ts#L6)
Codes for limits on record IDs, posting counts and storage allocations.
# knotkit/key-encoding
## Classes
[Section titled “Classes”](#classes)
* [KeyEncodingInvalidInputError](/reference/knotkit/key-encoding/classes/keyencodinginvalidinputerror/)
* [KeyEncodingParseError](/reference/knotkit/key-encoding/classes/keyencodingparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [KeyTuplePartValueByKind](/reference/knotkit/key-encoding/interfaces/keytuplepartvaluebykind/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [KeyEncodingInvalidInputErrorCode](/reference/knotkit/key-encoding/type-aliases/keyencodinginvalidinputerrorcode/)
* [KeyEncodingParseErrorCode](/reference/knotkit/key-encoding/type-aliases/keyencodingparseerrorcode/)
* [KeyEncodingErrorCode](/reference/knotkit/key-encoding/type-aliases/keyencodingerrorcode/)
* [KeyTuplePartKind](/reference/knotkit/key-encoding/type-aliases/keytuplepartkind/)
* [KeyDirection](/reference/knotkit/key-encoding/type-aliases/keydirection/)
* [KeyTuplePart](/reference/knotkit/key-encoding/type-aliases/keytuplepart/)
## Variables
[Section titled “Variables”](#variables)
* [KEY_ENCODING_INVALID_INPUT_ERROR_CODES](/reference/knotkit/key-encoding/variables/key_encoding_invalid_input_error_codes/)
* [KEY_ENCODING_PARSE_ERROR_CODES](/reference/knotkit/key-encoding/variables/key_encoding_parse_error_codes/)
* [KEY_ENCODING_ERROR_CODES](/reference/knotkit/key-encoding/variables/key_encoding_error_codes/)
* [KEY_TUPLE_PART_KINDS](/reference/knotkit/key-encoding/variables/key_tuple_part_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [compareBytes](/reference/knotkit/key-encoding/functions/comparebytes/)
* [commonPrefixLength](/reference/knotkit/key-encoding/functions/commonprefixlength/)
* [bytesPrefixEnd](/reference/knotkit/key-encoding/functions/bytesprefixend/)
* [encodeUint32Key](/reference/knotkit/key-encoding/functions/encodeuint32key/)
* [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/)
* [encodeInt32Key](/reference/knotkit/key-encoding/functions/encodeint32key/)
* [decodeInt32Key](/reference/knotkit/key-encoding/functions/decodeint32key/)
* [encodeUint64Key](/reference/knotkit/key-encoding/functions/encodeuint64key/)
* [decodeUint64Key](/reference/knotkit/key-encoding/functions/decodeuint64key/)
* [encodeInt64Key](/reference/knotkit/key-encoding/functions/encodeint64key/)
* [decodeInt64Key](/reference/knotkit/key-encoding/functions/decodeint64key/)
* [encodeFloat64Key](/reference/knotkit/key-encoding/functions/encodefloat64key/)
* [decodeFloat64Key](/reference/knotkit/key-encoding/functions/decodefloat64key/)
* [encodeBytesKey](/reference/knotkit/key-encoding/functions/encodebyteskey/)
* [decodeBytesKey](/reference/knotkit/key-encoding/functions/decodebyteskey/)
* [encodeStringKey](/reference/knotkit/key-encoding/functions/encodestringkey/)
* [decodeStringKey](/reference/knotkit/key-encoding/functions/decodestringkey/)
* [invertKeyBytes](/reference/knotkit/key-encoding/functions/invertkeybytes/)
* [encodeDescendingBytesKey](/reference/knotkit/key-encoding/functions/encodedescendingbyteskey/)
* [decodeDescendingBytesKey](/reference/knotkit/key-encoding/functions/decodedescendingbyteskey/)
* [encodeKeyTuple](/reference/knotkit/key-encoding/functions/encodekeytuple/)
* [decodeKeyTuple](/reference/knotkit/key-encoding/functions/decodekeytuple/)
# KeyEncodingInvalidInputError
Defined in: [packages/key-encoding/src/errors.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L32)
Thrown when a caller passes a value or offset outside a codec’s domain.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`KeyEncodingInvalidInputErrorCode`](/reference/knotkit/key-encoding/type-aliases/keyencodinginvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new KeyEncodingInvalidInputError**(`code`, `message`): `KeyEncodingInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_KEY_VALUE"` | `"INVALID_OFFSET"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`KeyEncodingInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_KEY_VALUE"` | `"INVALID_OFFSET"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/key-encoding"`
Defined in: [packages/key-encoding/src/errors.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L33)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# KeyEncodingParseError
Defined in: [packages/key-encoding/src/errors.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L37)
Thrown when bytes handed to a decoder are not an encoding this module produces.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`KeyEncodingParseErrorCode`](/reference/knotkit/key-encoding/type-aliases/keyencodingparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new KeyEncodingParseError**(`code`, `message`): `KeyEncodingParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"TRUNCATED_KEY"` | `"INVALID_ESCAPE_SEQUENCE"` | `"UNKNOWN_PART_TAG"` | `"INVALID_UTF8"` | `"NON_CANONICAL_FLOAT64"` | `"TRAILING_BYTES"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`KeyEncodingParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"TRUNCATED_KEY"` | `"INVALID_ESCAPE_SEQUENCE"` | `"UNKNOWN_PART_TAG"` | `"INVALID_UTF8"` | `"NON_CANONICAL_FLOAT64"` | `"TRAILING_BYTES"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/key-encoding"`
Defined in: [packages/key-encoding/src/errors.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L38)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# bytesPrefixEnd
> **bytesPrefixEnd**(`prefix`): `Uint8Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/key-encoding/src/bytes.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/bytes.ts#L56)
The smallest byte string greater than every key that starts with `prefix`, the exclusive upper bound of a prefix range scan: a key starts with `prefix` exactly when `prefix <= key < bytesPrefixEnd(prefix)`.
Drops trailing `0xff` bytes and increments the last remaining byte, returning a new array. Returns `undefined` when `prefix` is empty or every byte is `0xff`, because then no finite bound exists and the scan runs to the end.
## Parameters
[Section titled “Parameters”](#parameters)
### prefix
[Section titled “prefix”](#prefix)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`<`ArrayBufferLike`> | `undefined`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `prefix` is not a `Uint8Array`.
# commonPrefixLength
> **commonPrefixLength**(`left`, `right`): `number`
Defined in: [packages/key-encoding/src/bytes.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/bytes.ts#L35)
Count the leading bytes `left` and `right` share, from `0` through `min(left.byteLength, right.byteLength)`.
Runs in O(result) and, like [compareBytes](/reference/knotkit/key-encoding/functions/comparebytes/), does not validate its arguments.
## Parameters
[Section titled “Parameters”](#parameters)
### left
[Section titled “left”](#left)
`Uint8Array`
### right
[Section titled “right”](#right)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`number`
# compareBytes
> **compareBytes**(`left`, `right`): `-1` | `0` | `1`
Defined in: [packages/key-encoding/src/bytes.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/bytes.ts#L12)
Compare two byte strings in unsigned lexicographic order, the order an encoded key sorts in.
A proper prefix sorts before every longer string that extends it. The result is `-1`, `0`, or `1`, so the function is an `Order` for `knotkit/heap`, `knotkit/ordered-map`, `knotkit/sorted-merge`, or `Array.prototype.sort`.
Runs in O(min(left.byteLength, right.byteLength)) and does not validate its arguments, because it sits on the hot path of every comparison-based structure; pass `Uint8Array` values.
## Parameters
[Section titled “Parameters”](#parameters)
### left
[Section titled “left”](#left)
`Uint8Array`
### right
[Section titled “right”](#right)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`-1` | `0` | `1`
# decodeBytesKey
> **decodeBytesKey**(`bytes`, `offset?`): readonly \[`Uint8Array`<`ArrayBufferLike`>, `number`]
Defined in: [packages/key-encoding/src/scalars.ts:202](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L202)
Decode one `encodeBytesKey` encoding at `offset`, returning the byte string and the offset after its terminator.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly \[`Uint8Array`<`ArrayBufferLike`>, `number`]
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when the bytes end before the terminator, `INVALID_ESCAPE_SEQUENCE` when a `0x00` is followed by a byte other than `0xff` or `0x00`, or `TRAILING_BYTES` as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
# decodeDescendingBytesKey
> **decodeDescendingBytesKey**(`bytes`, `offset?`): readonly \[`Uint8Array`<`ArrayBufferLike`>, `number`]
Defined in: [packages/key-encoding/src/scalars.ts:279](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L279)
Decode one `encodeDescendingBytesKey` encoding at `offset`, returning the byte string and the offset after it.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly \[`Uint8Array`<`ArrayBufferLike`>, `number`]
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY`, `INVALID_ESCAPE_SEQUENCE`, or `TRAILING_BYTES`, as [decodeBytesKey](/reference/knotkit/key-encoding/functions/decodebyteskey/).
# decodeFloat64Key
> **decodeFloat64Key**(`bytes`, `offset?`): `number`
Defined in: [packages/key-encoding/src/scalars.ts:169](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L169)
Decode the 8-byte `encodeFloat64Key` encoding at `offset`.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when fewer than 8 bytes follow `offset`, `TRAILING_BYTES` as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/), or `NON_CANONICAL_FLOAT64` when the bytes hold a `NaN` or `-0` pattern, which no encoder writes.
# decodeInt32Key
> **decodeInt32Key**(`bytes`, `offset?`): `number`
Defined in: [packages/key-encoding/src/scalars.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L79)
Decode the 4-byte `encodeInt32Key` encoding at `offset`.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when fewer than 4 bytes follow `offset`, or `TRAILING_BYTES` as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
# decodeInt64Key
> **decodeInt64Key**(`bytes`, `offset?`): `bigint`
Defined in: [packages/key-encoding/src/scalars.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L136)
Decode the 8-byte `encodeInt64Key` encoding at `offset`.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when fewer than 8 bytes follow `offset`, or `TRAILING_BYTES` as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
# decodeKeyTuple
> **decodeKeyTuple**(`bytes`): readonly [`KeyTuplePart`](/reference/knotkit/key-encoding/type-aliases/keytuplepart/)\[]
Defined in: [packages/key-encoding/src/tuple.ts:302](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L302)
Decode an `encodeKeyTuple` key back into its parts. Every decoded part carries an explicit `direction`.
Accepts exactly the bytes `encodeKeyTuple` writes: re-encoding the result reproduces the input byte for byte. An empty array decodes to an empty tuple.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
readonly [`KeyTuplePart`](/reference/knotkit/key-encoding/type-aliases/keytuplepart/)\[]
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `bytes` is not a `Uint8Array`.
## Throws
[Section titled “Throws”](#throws-1)
`UNKNOWN_PART_TAG` for a tag that names no kind; `TRUNCATED_KEY` when a payload or terminator is cut off; `INVALID_ESCAPE_SEQUENCE` for a `0x00` not followed by `0xff` or `0x00`; `INVALID_UTF8` for a string payload that is not well-formed UTF-8; `NON_CANONICAL_FLOAT64` for a `NaN` or `-0` bit pattern.
# decodeStringKey
> **decodeStringKey**(`bytes`, `offset?`): readonly \[`string`, `number`]
Defined in: [packages/key-encoding/src/scalars.ts:230](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L230)
Decode one `encodeStringKey` encoding at `offset`, returning the string and the offset after its terminator.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly \[`string`, `number`]
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY`, `INVALID_ESCAPE_SEQUENCE`, or `TRAILING_BYTES`, as [decodeBytesKey](/reference/knotkit/key-encoding/functions/decodebyteskey/), or `INVALID_UTF8` when the payload is not well-formed UTF-8.
# decodeUint32Key
> **decodeUint32Key**(`bytes`, `offset?`): `number`
Defined in: [packages/key-encoding/src/scalars.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L51)
Decode the 4-byte `encodeUint32Key` encoding.
Every `decode*Key` function follows one rule for `offset`. Without it, `bytes` must be exactly one key and anything after the key is `TRAILING_BYTES`. With it, the key is read in place at `offset` and the bytes after it are left to the caller, which is how a hand-built composite key is read one field at a time.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `bytes` is not a `Uint8Array`, or `INVALID_OFFSET` when `offset` is not an integer in `0 .. bytes.byteLength`.
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when fewer than 4 bytes follow `offset`, or `TRAILING_BYTES` when `offset` is omitted and `bytes` is longer than 4 bytes.
# decodeUint64Key
> **decodeUint64Key**(`bytes`, `offset?`): `bigint`
Defined in: [packages/key-encoding/src/scalars.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L107)
Decode the 8-byte `encodeUint64Key` encoding at `offset`.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset?
[Section titled “offset?”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` or `INVALID_OFFSET`, as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
## Throws
[Section titled “Throws”](#throws-1)
`TRUNCATED_KEY` when fewer than 8 bytes follow `offset`, or `TRAILING_BYTES` as [decodeUint32Key](/reference/knotkit/key-encoding/functions/decodeuint32key/).
# encodeBytesKey
> **encodeBytesKey**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:186](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L186)
Encode a byte string so that `compareBytes` orders the keys as the byte strings themselves, and so the key is self-delimiting: it can be followed by more key bytes without changing the order.
Writes each `0x00` as `0x00 0xff` and ends with `0x00 0x00`. A byte string that is a prefix of another therefore sorts first, exactly as under [compareBytes](/reference/knotkit/key-encoding/functions/comparebytes/). Costs `value.byteLength + 2` bytes plus one per `0x00`.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not a `Uint8Array`.
# encodeDescendingBytesKey
> **encodeDescendingBytesKey**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:264](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L264)
Encode a byte string so that keys sort in reverse byte-string order, longer before shorter on a shared prefix.
The bitwise complement of [encodeBytesKey](/reference/knotkit/key-encoding/functions/encodebyteskey/). Because that encoding is self-delimiting, no key is a prefix of another, so complementing it reverses the order exactly.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not a `Uint8Array`.
# encodeFloat64Key
> **encodeFloat64Key**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:153](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L153)
Encode a double as 8 bytes that sort in numeric order: `-Infinity` first, `Infinity` last.
Takes the IEEE-754 big-endian bits, flips the sign bit of a non-negative value and every bit of a negative one. `-0` is written as `+0`, so the two zeros share one key, as they do under `===`.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`number`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is `NaN` or not a number, because `NaN` has no place in a total order.
# encodeInt32Key
> **encodeInt32Key**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L64)
Encode a signed 32-bit integer as 4 big-endian bytes with the sign bit flipped, so negative values sort first.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`number`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not an integer in `-2^31 .. 2^31 - 1`.
# encodeInt64Key
> **encodeInt64Key**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L121)
Encode a signed 64-bit `bigint` as 8 big-endian bytes with the sign bit flipped.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`bigint`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not a `bigint` in `-(2n ** 63n) .. 2n ** 63n - 1n`.
# encodeKeyTuple
> **encodeKeyTuple**(`parts`): `Uint8Array`
Defined in: [packages/key-encoding/src/tuple.ts:219](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L219)
Encode a composite key so that `compareBytes` orders encoded tuples lexicographically by part, each part in its own direction: the first part decides, the second breaks ties, and a tuple sorts before every longer tuple it is a prefix of.
Each part is a one-byte tag naming its kind and direction, then its payload: the fixed-width scalar encoding, or the escaped encoding for `bytes` and `string`. A descending part writes the bitwise complement of its ascending payload; because every payload is self-delimiting, that reverses its order exactly, including between byte strings of different lengths. Two tuples compare meaningfully only part by part over the same kinds, as in one index schema.
Runs in O(total payload bytes) and allocates the result once.
## Parameters
[Section titled “Parameters”](#parameters)
### parts
[Section titled “parts”](#parts)
readonly [`KeyTuplePart`](/reference/knotkit/key-encoding/type-aliases/keytuplepart/)\[]
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `parts` is not an array, a part’s `kind` or `direction` is unknown, or its `value` is outside the kind’s domain, as the matching `encode*Key` would report.
# encodeStringKey
> **encodeStringKey**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:219](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L219)
Encode a string as its UTF-8 bytes under [encodeBytesKey](/reference/knotkit/key-encoding/functions/encodebyteskey/), so keys sort by Unicode code point.
Code point order equals JavaScript’s `<` on strings except where a supplementary character (U+10000 and above, held as a surrogate pair) meets a character in U+E000 .. U+FFFF: `<` compares UTF-16 code units and puts the supplementary character first, code point order puts it last.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`string`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not a string or holds an unpaired UTF-16 surrogate, which UTF-8 cannot represent; refusing it keeps every decoded key equal to the string encoded.
# encodeUint32Key
> **encodeUint32Key**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L31)
Encode an unsigned 32-bit integer as 4 big-endian bytes, so `compareBytes` orders the keys as the integers.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`number`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not an integer in `0 .. 2^32 - 1`.
# encodeUint64Key
> **encodeUint64Key**(`value`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L92)
Encode an unsigned 64-bit `bigint` as 8 big-endian bytes.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`bigint`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `value` is not a `bigint` in `0n .. 2n ** 64n - 1n`.
# invertKeyBytes
> **invertKeyBytes**(`bytes`): `Uint8Array`
Defined in: [packages/key-encoding/src/scalars.ts:245](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/scalars.ts#L245)
The bitwise complement of every byte, as a new array. Reverses the order of fixed-width keys: for two keys of the same length, `compareBytes(invertKeyBytes(a), invertKeyBytes(b)) === compareBytes(b, a)`.
Inverting does not reverse keys of different lengths where one is a prefix of the other; use [encodeDescendingBytesKey](/reference/knotkit/key-encoding/functions/encodedescendingbyteskey/) for a variable-length descending key.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
`INVALID_KEY_VALUE` when `bytes` is not a `Uint8Array`.
# KeyTuplePartValueByKind
Defined in: [packages/key-encoding/src/tuple.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L41)
The JavaScript value each tuple part kind holds.
## Properties
[Section titled “Properties”](#properties)
### bytes
[Section titled “bytes”](#bytes)
> `readonly` **bytes**: `Uint8Array`
Defined in: [packages/key-encoding/src/tuple.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L42)
***
### string
[Section titled “string”](#string)
> `readonly` **string**: `string`
Defined in: [packages/key-encoding/src/tuple.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L43)
***
### uint32
[Section titled “uint32”](#uint32)
> `readonly` **uint32**: `number`
Defined in: [packages/key-encoding/src/tuple.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L44)
***
### int32
[Section titled “int32”](#int32)
> `readonly` **int32**: `number`
Defined in: [packages/key-encoding/src/tuple.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L45)
***
### uint64
[Section titled “uint64”](#uint64)
> `readonly` **uint64**: `bigint`
Defined in: [packages/key-encoding/src/tuple.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L46)
***
### int64
[Section titled “int64”](#int64)
> `readonly` **int64**: `bigint`
Defined in: [packages/key-encoding/src/tuple.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L47)
***
### float64
[Section titled “float64”](#float64)
> `readonly` **float64**: `number`
Defined in: [packages/key-encoding/src/tuple.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L48)
# KeyDirection
> **KeyDirection** = `"ascending"` | `"descending"`
Defined in: [packages/key-encoding/src/tuple.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L38)
The direction a tuple part sorts in.
# KeyEncodingErrorCode
> **KeyEncodingErrorCode** = [`KeyEncodingInvalidInputErrorCode`](/reference/knotkit/key-encoding/type-aliases/keyencodinginvalidinputerrorcode/) | [`KeyEncodingParseErrorCode`](/reference/knotkit/key-encoding/type-aliases/keyencodingparseerrorcode/)
Defined in: [packages/key-encoding/src/errors.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L23)
A machine-readable error code emitted by `knotkit/key-encoding`.
# KeyEncodingInvalidInputErrorCode
> **KeyEncodingInvalidInputErrorCode** = *typeof* [`KEY_ENCODING_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/key-encoding/variables/key_encoding_invalid_input_error_codes/)\[`number`]
Defined in: [packages/key-encoding/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L17)
A machine-readable caller-contract code emitted by `knotkit/key-encoding`.
# KeyEncodingParseErrorCode
> **KeyEncodingParseErrorCode** = *typeof* [`KEY_ENCODING_PARSE_ERROR_CODES`](/reference/knotkit/key-encoding/variables/key_encoding_parse_error_codes/)\[`number`]
Defined in: [packages/key-encoding/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L20)
A machine-readable decode code emitted by `knotkit/key-encoding`.
# KeyTuplePart
> **KeyTuplePart** = `{ readonly [K in KeyTuplePartKind]: { kind: K; value: KeyTuplePartValueByKind[K]; direction?: KeyDirection } }`\[[`KeyTuplePartKind`](/reference/knotkit/key-encoding/type-aliases/keytuplepartkind/)]
Defined in: [packages/key-encoding/src/tuple.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L55)
One element of a composite key: a value, the domain it belongs to, and the direction it sorts in, `'ascending'` when omitted. Narrowing on `kind` narrows `value`.
# KeyTuplePartKind
> **KeyTuplePartKind** = *typeof* [`KEY_TUPLE_PART_KINDS`](/reference/knotkit/key-encoding/variables/key_tuple_part_kinds/)\[`number`]
Defined in: [packages/key-encoding/src/tuple.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L35)
A value domain a tuple part can hold.
# KEY_ENCODING_ERROR_CODES
> `const` **KEY_ENCODING_ERROR_CODES**: readonly \[`...typeof KEY_ENCODING_INVALID_INPUT_ERROR_CODES`, `...typeof KEY_ENCODING_PARSE_ERROR_CODES`]
Defined in: [packages/key-encoding/src/errors.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L26)
Every error code emitted by `knotkit/key-encoding`, in stable category order.
# KEY_ENCODING_INVALID_INPUT_ERROR_CODES
> `const` **KEY_ENCODING_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_KEY_VALUE"`, `"INVALID_OFFSET"`]
Defined in: [packages/key-encoding/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L4)
Every caller-contract error code emitted by [KeyEncodingInvalidInputError](/reference/knotkit/key-encoding/classes/keyencodinginvalidinputerror/).
# KEY_ENCODING_PARSE_ERROR_CODES
> `const` **KEY_ENCODING_PARSE_ERROR_CODES**: readonly \[`"TRUNCATED_KEY"`, `"INVALID_ESCAPE_SEQUENCE"`, `"UNKNOWN_PART_TAG"`, `"INVALID_UTF8"`, `"NON_CANONICAL_FLOAT64"`, `"TRAILING_BYTES"`]
Defined in: [packages/key-encoding/src/errors.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/errors.ts#L7)
Every decode error code emitted by [KeyEncodingParseError](/reference/knotkit/key-encoding/classes/keyencodingparseerror/).
# KEY_TUPLE_PART_KINDS
> `const` **KEY_TUPLE_PART_KINDS**: readonly \[`"bytes"`, `"string"`, `"uint32"`, `"int32"`, `"uint64"`, `"int64"`, `"float64"`]
Defined in: [packages/key-encoding/src/tuple.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/key-encoding/src/tuple.ts#L31)
Every value domain a tuple part can hold, in tag order. The position of a kind is its wire tag minus one, so the order is part of the format: append new kinds, never reorder.
# knotkit/ordered-map
## Classes
[Section titled “Classes”](#classes)
* [OrderedMapInvalidInputError](/reference/knotkit/ordered-map/classes/orderedmapinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [OrderedMap](/reference/knotkit/ordered-map/interfaces/orderedmap/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [OrderedMapInvalidInputErrorCode](/reference/knotkit/ordered-map/type-aliases/orderedmapinvalidinputerrorcode/)
* [OrderedMapErrorCode](/reference/knotkit/ordered-map/type-aliases/orderedmaperrorcode/)
* [OrderedMapKind](/reference/knotkit/ordered-map/type-aliases/orderedmapkind/)
* [OrderedMapFactory](/reference/knotkit/ordered-map/type-aliases/orderedmapfactory/)
* [OrderedMapBounds](/reference/knotkit/ordered-map/type-aliases/orderedmapbounds/)
## Variables
[Section titled “Variables”](#variables)
* [ORDERED_MAP_INVALID_INPUT_ERROR_CODES](/reference/knotkit/ordered-map/variables/ordered_map_invalid_input_error_codes/)
* [ORDERED_MAP_ERROR_CODES](/reference/knotkit/ordered-map/variables/ordered_map_error_codes/)
* [\_\_ORDERED_MAP_LAYOUTS](/reference/knotkit/ordered-map/variables/ordered_map_layouts/)
* [ORDERED_MAP_KINDS](/reference/knotkit/ordered-map/variables/ordered_map_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [bTreeOrderedMap](/reference/knotkit/ordered-map/functions/btreeorderedmap/)
* [indexedSkipListOrderedMap](/reference/knotkit/ordered-map/functions/indexedskiplistorderedmap/)
# OrderedMapInvalidInputError
Defined in: [packages/ordered-map/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L14)
A positional read, random draw or iterator step broke the map’s contract.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`OrderedMapInvalidInputErrorCode`](/reference/knotkit/ordered-map/type-aliases/orderedmapinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new OrderedMapInvalidInputError**(`code`, `message`): `OrderedMapInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_INDEX"` | `"MODIFIED_DURING_ITERATION"` | `"INVALID_SOURCE_VALUE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`OrderedMapInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_INDEX"` | `"MODIFIED_DURING_ITERATION"` | `"INVALID_SOURCE_VALUE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/ordered-map"`
Defined in: [packages/ordered-map/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L15)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# bTreeOrderedMap
> **bTreeOrderedMap**<`K`, `V`>(`order`): [`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
Defined in: [packages/ordered-map/src/b-tree-ordered-map.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/b-tree-ordered-map.ts#L55)
Create an empty B-tree ordered map: a B+ tree with linked leaves and per-child entry counts on each branch. Supply a stable total order and keep comparison keys unchanged while stored. The order may not mutate the map.
Every search, write, rank, selection, `ceiling` and `floor` takes worst-case O(log n) time. A bounded walk in either direction costs one descent plus O(k) for k results.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
## Returns
[Section titled “Returns”](#returns)
[`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
## See
[Section titled “See”](#see)
Douglas Comer, The Ubiquitous B-Tree, ACM Computing Surveys 11(2), 1979.
# indexedSkipListOrderedMap
> **indexedSkipListOrderedMap**<`K`, `V`>(`order`, `random?`): [`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
Defined in: [packages/ordered-map/src/indexed-skip-list-ordered-map.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/indexed-skip-list-ordered-map.ts#L26)
Create an empty indexed skip list. The default generator is a fresh splitmix32(0). Supply a stable total order and keep comparison keys unchanged while stored. Neither the order nor the random source may mutate the map. Searches, writes, rank and selection take expected O(log n) time under independent uniform draws; a bounded walk in either direction adds O(k) for k results.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
### random?
[Section titled “random?”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/) = `...`
## Returns
[Section titled “Returns”](#returns)
[`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
## See
[Section titled “See”](#see)
William Pugh, A Skip List Cookbook, section 3.4.
# OrderedMap
Defined in: [packages/ordered-map/src/ordered-map.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L17)
Key equivalence is comparator equality. Each layout documents its own time bounds.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"b-tree"` | `"indexed-skip-list"`
Defined in: [packages/ordered-map/src/ordered-map.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L18)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/ordered-map/src/ordered-map.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L19)
***
### set
[Section titled “set”](#set)
> `readonly` **set**: (`key`, `value`) => `void`
Defined in: [packages/ordered-map/src/ordered-map.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L23)
Insert or replace a value. Replacement preserves the original stored key.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With INVALID_SOURCE_VALUE when a randomized layout draws outside \[0, 1).
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`key`) => `V` | `undefined`
Defined in: [packages/ordered-map/src/ordered-map.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L25)
Read a value, or undefined when absent. Use has to distinguish a stored undefined.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
#### Returns
[Section titled “Returns”](#returns-1)
`V` | `undefined`
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`key`) => `boolean`
Defined in: [packages/ordered-map/src/ordered-map.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L26)
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### key
[Section titled “key”](#key-2)
`K`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
***
### delete
[Section titled “delete”](#delete)
> `readonly` **delete**: (`key`) => `boolean`
Defined in: [packages/ordered-map/src/ordered-map.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L28)
Remove an equivalent key and report whether it existed.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### key
[Section titled “key”](#key-3)
`K`
#### Returns
[Section titled “Returns”](#returns-3)
`boolean`
***
### rank
[Section titled “rank”](#rank)
> `readonly` **rank**: (`key`) => `number`
Defined in: [packages/ordered-map/src/ordered-map.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L30)
Count keys at or below the given key in comparator order.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### key
[Section titled “key”](#key-4)
`K`
#### Returns
[Section titled “Returns”](#returns-4)
`number`
***
### at
[Section titled “at”](#at)
> `readonly` **at**: (`position`) => readonly \[`K`, `V`]
Defined in: [packages/ordered-map/src/ordered-map.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L34)
Read the entry at a zero-based position. Negative positions count from the end.
#### Parameters
[Section titled “Parameters”](#parameters-5)
##### position
[Section titled “position”](#position)
`number`
#### Returns
[Section titled “Returns”](#returns-5)
readonly \[`K`, `V`]
#### Throws
[Section titled “Throws”](#throws-1)
With INVALID_INDEX for a noninteger or out-of-range position.
***
### ceiling
[Section titled “ceiling”](#ceiling)
> `readonly` **ceiling**: (`key`) => readonly \[`K`, `V`] | `undefined`
Defined in: [packages/ordered-map/src/ordered-map.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L36)
Read the entry with the smallest stored key at or above `key`, or undefined when every stored key is below it.
#### Parameters
[Section titled “Parameters”](#parameters-6)
##### key
[Section titled “key”](#key-5)
`K`
#### Returns
[Section titled “Returns”](#returns-6)
readonly \[`K`, `V`] | `undefined`
***
### floor
[Section titled “floor”](#floor)
> `readonly` **floor**: (`key`) => readonly \[`K`, `V`] | `undefined`
Defined in: [packages/ordered-map/src/ordered-map.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L38)
Read the entry with the largest stored key at or below `key`, or undefined when every stored key is above it.
#### Parameters
[Section titled “Parameters”](#parameters-7)
##### key
[Section titled “key”](#key-6)
`K`
#### Returns
[Section titled “Returns”](#returns-7)
readonly \[`K`, `V`] | `undefined`
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: (…`bounds`) => `IterableIterator`\
Defined in: [packages/ordered-map/src/ordered-map.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L43)
Walk every entry, `[start, +∞)`, or the half-open range `[start, end)` in ascending comparator order. Equal or reversed bounds yield nothing.
#### Parameters
[Section titled “Parameters”](#parameters-8)
##### bounds
[Section titled “bounds”](#bounds)
…[`OrderedMapBounds`](/reference/knotkit/ordered-map/type-aliases/orderedmapbounds/)<`K`>
#### Returns
[Section titled “Returns”](#returns-8)
`IterableIterator`\
#### Throws
[Section titled “Throws”](#throws-2)
With MODIFIED_DURING_ITERATION on advancement after a set or successful deletion.
***
### entriesReverse
[Section titled “entriesReverse”](#entriesreverse)
> `readonly` **entriesReverse**: (…`bounds`) => `IterableIterator`\
Defined in: [packages/ordered-map/src/ordered-map.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L47)
Walk exactly the entries `entries(...bounds)` walks, in descending comparator order.
#### Parameters
[Section titled “Parameters”](#parameters-9)
##### bounds
[Section titled “bounds”](#bounds-1)
…[`OrderedMapBounds`](/reference/knotkit/ordered-map/type-aliases/orderedmapbounds/)<`K`>
#### Returns
[Section titled “Returns”](#returns-9)
`IterableIterator`\
#### Throws
[Section titled “Throws”](#throws-3)
With MODIFIED_DURING_ITERATION on advancement after a set or successful deletion.
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`\
Defined in: [packages/ordered-map/src/ordered-map.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L51)
The same full walk as entries().
#### Returns
[Section titled “Returns”](#returns-10)
`IterableIterator`\
#### Throws
[Section titled “Throws”](#throws-4)
With MODIFIED_DURING_ITERATION on advancement after a set or successful deletion.
# OrderedMapBounds
> **OrderedMapBounds**<`K`> = \[] | \[`start`: `K`] | \[`start`: `K`, `end`: `K`]
Defined in: [packages/ordered-map/src/ordered-map.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L14)
Optional walk bounds: none for every entry, `[start]` for `[start, +∞)`, `[start, end]` for `[start, end)`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
# OrderedMapErrorCode
> **OrderedMapErrorCode** = [`OrderedMapInvalidInputErrorCode`](/reference/knotkit/ordered-map/type-aliases/orderedmapinvalidinputerrorcode/)
Defined in: [packages/ordered-map/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L11)
# OrderedMapFactory
> **OrderedMapFactory** = <`K`, `V`>(`order`) => [`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
Defined in: [packages/ordered-map/src/ordered-map.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L11)
The constructor shape every layout shares: an empty map ordered by `order`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`K`>
## Returns
[Section titled “Returns”](#returns)
[`OrderedMap`](/reference/knotkit/ordered-map/interfaces/orderedmap/)<`K`, `V`>
# OrderedMapInvalidInputErrorCode
> **OrderedMapInvalidInputErrorCode** = *typeof* [`ORDERED_MAP_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/ordered-map/variables/ordered_map_invalid_input_error_codes/)\[`number`]
Defined in: [packages/ordered-map/src/errors.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L10)
# OrderedMapKind
> **OrderedMapKind** = *typeof* [`ORDERED_MAP_KINDS`](/reference/knotkit/ordered-map/variables/ordered_map_kinds/)\[`number`]
Defined in: [packages/ordered-map/src/ordered-map.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L8)
# ORDERED_MAP_ERROR_CODES
> `const` **ORDERED_MAP_ERROR_CODES**: *typeof* [`ORDERED_MAP_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/ordered-map/variables/ordered_map_invalid_input_error_codes/) = `ORDERED_MAP_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/ordered-map/src/errors.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L8)
# ORDERED_MAP_INVALID_INPUT_ERROR_CODES
> `const` **ORDERED_MAP_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_INDEX"`, `"INVALID_SOURCE_VALUE"`, `"MODIFIED_DURING_ITERATION"`]
Defined in: [packages/ordered-map/src/errors.ts:3](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/errors.ts#L3)
# ORDERED_MAP_KINDS
> `const` **ORDERED_MAP_KINDS**: readonly \[`"b-tree"`, `"indexed-skip-list"`]
Defined in: [packages/ordered-map/src/ordered-map.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/ordered-map.ts#L4)
Every ordered map layout, with the recommended default first.
# __ORDERED_MAP_LAYOUTS
> `const` **\_\_ORDERED_MAP_LAYOUTS**: `Readonly`<{ `b-tree`: *typeof* [`bTreeOrderedMap`](/reference/knotkit/ordered-map/functions/btreeorderedmap/); `indexed-skip-list`: *typeof* [`indexedSkipListOrderedMap`](/reference/knotkit/ordered-map/functions/indexedskiplistorderedmap/); }>
Defined in: [packages/ordered-map/src/layouts.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/ordered-map/src/layouts.ts#L11)
Every ordered map layout this package constructs, keyed by the `kind` it reports.
Exported so a property test, a benchmark, or a `problems/*` preset can sweep every layout without naming one. A caller building one map imports `bTreeOrderedMap` or `indexedSkipListOrderedMap` directly.
# knotkit/prefix-index
## Classes
[Section titled “Classes”](#classes)
* [PrefixIndexInvalidInputError](/reference/knotkit/prefix-index/classes/prefixindexinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [PrefixIndex](/reference/knotkit/prefix-index/interfaces/prefixindex/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [PrefixIndexInvalidInputErrorCode](/reference/knotkit/prefix-index/type-aliases/prefixindexinvalidinputerrorcode/)
* [PrefixIndexErrorCode](/reference/knotkit/prefix-index/type-aliases/prefixindexerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [PREFIX_INDEX_INVALID_INPUT_ERROR_CODES](/reference/knotkit/prefix-index/variables/prefix_index_invalid_input_error_codes/)
* [PREFIX_INDEX_ERROR_CODES](/reference/knotkit/prefix-index/variables/prefix_index_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [prefixIndex](/reference/knotkit/prefix-index/functions/prefixindex/)
# PrefixIndexInvalidInputError
Defined in: [packages/prefix-index/src/errors.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L19)
A prefix enumeration limit is outside the nonnegative safe integers.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`PrefixIndexInvalidInputErrorCode`](/reference/knotkit/prefix-index/type-aliases/prefixindexinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new PrefixIndexInvalidInputError**(`code`, `message`): `PrefixIndexInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_LIMIT"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`PrefixIndexInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_LIMIT"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/prefix-index"`
Defined in: [packages/prefix-index/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L20)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# prefixIndex
> **prefixIndex**(`input`): [`PrefixIndex`](/reference/knotkit/prefix-index/interfaces/prefixindex/)
Defined in: [packages/prefix-index/src/prefix-index.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L26)
Snapshot an iterable of strings as sorted, distinct keys. Keys compare by UTF-16 code units. Build takes expected O(n) set operations for n input keys and O(u log(u + 1)) comparisons for u distinct keys. Retained space is O(u), excluding the strings themselves. Errors from the input iterable propagate.
## Parameters
[Section titled “Parameters”](#parameters)
### input
[Section titled “input”](#input)
`Iterable`<`string`>
## Returns
[Section titled “Returns”](#returns)
[`PrefixIndex`](/reference/knotkit/prefix-index/interfaces/prefixindex/)
# PrefixIndex
Defined in: [packages/prefix-index/src/prefix-index.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L4)
A read-only set of string keys in UTF-16 code unit order.
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/prefix-index/src/prefix-index.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L6)
Number of distinct keys.
***
### keys
[Section titled “keys”](#keys)
> `readonly` **keys**: () => `IterableIterator`<`string`>
Defined in: [packages/prefix-index/src/prefix-index.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L8)
Iterate all keys in ascending order.
#### Returns
[Section titled “Returns”](#returns)
`IterableIterator`<`string`>
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<`string`>
Defined in: [packages/prefix-index/src/prefix-index.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L10)
The same function as `keys`.
#### Returns
[Section titled “Returns”](#returns-1)
`IterableIterator`<`string`>
***
### keysWithPrefix
[Section titled “keysWithPrefix”](#keyswithprefix)
> `readonly` **keysWithPrefix**: (`prefix`, `limit`) => `IterableIterator`<`string`>
Defined in: [packages/prefix-index/src/prefix-index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/prefix-index.ts#L18)
Lazily yield up to `limit` distinct keys beginning with `prefix`, in ascending order. The empty prefix matches every key. Zero yields no keys without searching. For n distinct keys and k results, iteration takes O(log(n + 1) + k) string comparisons and O(1) extra space. The cost of comparing strings depends on their lengths.
#### Parameters
[Section titled “Parameters”](#parameters)
##### prefix
[Section titled “prefix”](#prefix)
`string`
##### limit
[Section titled “limit”](#limit)
`number`
#### Returns
[Section titled “Returns”](#returns-2)
`IterableIterator`<`string`>
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_LIMIT` if the limit is outside the nonnegative safe integers.
# PrefixIndexErrorCode
> **PrefixIndexErrorCode** = *typeof* [`PREFIX_INDEX_ERROR_CODES`](/reference/knotkit/prefix-index/variables/prefix_index_error_codes/)\[`number`]
Defined in: [packages/prefix-index/src/errors.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L16)
# PrefixIndexInvalidInputErrorCode
> **PrefixIndexInvalidInputErrorCode** = *typeof* `invalidInputCodes`\[`number`]
Defined in: [packages/prefix-index/src/errors.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L9)
# PREFIX_INDEX_ERROR_CODES
> `const` **PREFIX_INDEX_ERROR_CODES**: readonly [`PrefixIndexInvalidInputErrorCode`](/reference/knotkit/prefix-index/type-aliases/prefixindexinvalidinputerrorcode/)\[]
Defined in: [packages/prefix-index/src/errors.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L12)
All error codes emitted by `knotkit/prefix-index`.
# PREFIX_INDEX_INVALID_INPUT_ERROR_CODES
> `const` **PREFIX_INDEX_INVALID_INPUT_ERROR_CODES**: `Readonly`<*typeof* `invalidInputCodes`>
Defined in: [packages/prefix-index/src/errors.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prefix-index/src/errors.ts#L6)
Codes for invalid prefix enumeration limits.
# knotkit/prng
## Classes
[Section titled “Classes”](#classes)
* [PrngInvalidInputError](/reference/knotkit/prng/classes/prnginvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [Xoroshiro128StarStar](/reference/knotkit/prng/interfaces/xoroshiro128starstar/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [PrngInvalidInputErrorCode](/reference/knotkit/prng/type-aliases/prnginvalidinputerrorcode/)
* [PrngErrorCode](/reference/knotkit/prng/type-aliases/prngerrorcode/)
* [RandomSource](/reference/knotkit/prng/type-aliases/randomsource/)
* [RandomSource64](/reference/knotkit/prng/type-aliases/randomsource64/)
* [Xoroshiro128StarStarState](/reference/knotkit/prng/type-aliases/xoroshiro128starstarstate/)
## Variables
[Section titled “Variables”](#variables)
* [PRNG_INVALID_INPUT_ERROR_CODES](/reference/knotkit/prng/variables/prng_invalid_input_error_codes/)
* [PRNG_ERROR_CODES](/reference/knotkit/prng/variables/prng_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [splitmix32](/reference/knotkit/prng/functions/splitmix32/)
* [uniformInt](/reference/knotkit/prng/functions/uniformint/)
* [uniformInt64](/reference/knotkit/prng/functions/uniformint64/)
* [xoroshiro128StarStar](/reference/knotkit/prng/functions/xoroshiro128starstar/)
# PrngInvalidInputError
Defined in: [packages/prng/src/errors.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L24)
Thrown when a PRNG operation receives an invalid bound, source value, or generator state.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`PrngInvalidInputErrorCode`](/reference/knotkit/prng/type-aliases/prnginvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new PrngInvalidInputError**(`code`, `message`): `PrngInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_BOUND"` | `"INVALID_SOURCE_VALUE"` | `"INVALID_STATE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`PrngInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_BOUND"` | `"INVALID_SOURCE_VALUE"` | `"INVALID_STATE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/prng"`
Defined in: [packages/prng/src/errors.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L25)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# splitmix32
> **splitmix32**(`seed`): () => `number`
Defined in: [packages/prng/src/splitmix32.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/splitmix32.ts#L28)
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by `0x9e3779b9`. This constant equals `floor(2^32 / phi)`, where `phi` is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants `0x21f0aaad` and `0x735a2d97` from the [hash-prospector](https://github.com/skeeto/hash-prospector) search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.
`Math.imul` and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to `[0, 1)`.
The SplitMix family was introduced by Steele, Lea, and Flood in [Fast Splittable Pseudorandom Number Generators](https://dl.acm.org/doi/10.1145/2660193.2660195).
This generator is not cryptographically secure. Use `crypto.getRandomValues()` when unpredictability matters.
## Parameters
[Section titled “Parameters”](#parameters)
### seed
[Section titled “seed”](#seed)
`number`
Initial seed, coerced to a signed 32-bit integer.
## Returns
[Section titled “Returns”](#returns)
A stateful function that returns the next value in the range `[0, 1)`.
() => `number`
# uniformInt
> **uniformInt**(`random`, `upperExclusive`): `number`
Defined in: [packages/prng/src/uniform-int.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/uniform-int.ts#L32)
Draw an integer uniformly from `0..upperExclusive - 1`.
Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When the requested range does not divide 2^32 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 32-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.
The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.
Consumes one source draw in the common case. The rejection region is always smaller than `upperExclusive`, so fewer than half of all draws are rejected and the expected number of draws is below two.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
Function returning values in `[0, 1)`.
### upperExclusive
[Section titled “upperExclusive”](#upperexclusive)
`number`
Exclusive upper bound, from 1 through 2^32.
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_BOUND` when the bound is not an integer in `1..2^32`, or `INVALID_SOURCE_VALUE` when the source returns a value outside `[0, 1)`.
# uniformInt64
> **uniformInt64**(`random`, `upperExclusive`): `bigint`
Defined in: [packages/prng/src/uniform-int64.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/uniform-int64.ts#L35)
Draw an integer uniformly from `0..upperExclusive - 1`.
This is the 64-bit counterpart of `uniformInt`. It consumes a source that already returns unsigned 64-bit draws, so no floating-point step stands between the generator and the sample, and bounds above 2^32 stay exact.
When the requested range does not divide 2^64 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 64-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.
The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.
Consumes one source draw in the common case. The rejection region is always smaller than `upperExclusive`, so fewer than half of all draws are rejected and the expected number of draws is below two.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource64`](/reference/knotkit/prng/type-aliases/randomsource64/)
Function returning unsigned 64-bit values in `[0, 2^64)`.
### upperExclusive
[Section titled “upperExclusive”](#upperexclusive)
`bigint`
Exclusive upper bound, from 1 through 2^64.
## Returns
[Section titled “Returns”](#returns)
`bigint`
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_BOUND` when the bound is not a bigint in `1..2^64`, or `INVALID_SOURCE_VALUE` when the source returns a value outside `[0, 2^64)`.
# xoroshiro128StarStar
> **xoroshiro128StarStar**(`initialState`): [`Xoroshiro128StarStar`](/reference/knotkit/prng/interfaces/xoroshiro128starstar/)
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:90](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L90)
Create a xoroshiro128\*\* 1.0 pseudorandom number generator.
The two input words are reduced modulo 2^64. They must not both reduce to zero because the all-zero state is fixed and would only emit zeroes. Each call to `next()` runs in constant time, mutates the private 128-bit state, and returns the same unsigned 64-bit value as the reference C implementation.
`jump()` advances by 2^64 outputs and `longJump()` advances by 2^96 outputs. Both run in constant space and a fixed 128 state transitions.
This generator is not cryptographically secure. Use `crypto.getRandomValues()` when unpredictability matters.
## Parameters
[Section titled “Parameters”](#parameters)
### initialState
[Section titled “initialState”](#initialstate)
[`Xoroshiro128StarStarState`](/reference/knotkit/prng/type-aliases/xoroshiro128starstarstate/)
Two integers representing the initial 64-bit state words.
## Returns
[Section titled “Returns”](#returns)
[`Xoroshiro128StarStar`](/reference/knotkit/prng/interfaces/xoroshiro128starstar/)
A generator with private state and fixed-distance jump operations.
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_STATE` when the state does not contain two bigints or both words reduce to zero modulo 2^64.
# Xoroshiro128StarStar
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L25)
A stateful xoroshiro128\*\* generator and its fixed-distance jump operations.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"xoroshiro128-star-star"`
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L27)
Serializable identifier for this generator implementation.
***
### next
[Section titled “next”](#next)
> `readonly` **next**: () => `bigint`
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L30)
Advance the state once and return an unsigned 64-bit value.
#### Returns
[Section titled “Returns”](#returns)
`bigint`
***
### jump
[Section titled “jump”](#jump)
> `readonly` **jump**: () => `void`
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L33)
Advance the state by 2^64 calls to [Xoroshiro128StarStar.next](/reference/knotkit/prng/interfaces/xoroshiro128starstar/#next).
#### Returns
[Section titled “Returns”](#returns-1)
`void`
***
### longJump
[Section titled “longJump”](#longjump)
> `readonly` **longJump**: () => `void`
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L36)
Advance the state by 2^96 calls to [Xoroshiro128StarStar.next](/reference/knotkit/prng/interfaces/xoroshiro128starstar/#next).
#### Returns
[Section titled “Returns”](#returns-2)
`void`
# PrngErrorCode
> **PrngErrorCode** = [`PrngInvalidInputErrorCode`](/reference/knotkit/prng/type-aliases/prnginvalidinputerrorcode/)
Defined in: [packages/prng/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L21)
A machine-readable error code emitted by `knotkit/prng`.
# PrngInvalidInputErrorCode
> **PrngInvalidInputErrorCode** = *typeof* [`PRNG_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/prng/variables/prng_invalid_input_error_codes/)\[`number`]
Defined in: [packages/prng/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L18)
A machine-readable invalid-input code emitted by `knotkit/prng`.
# RandomSource
> **RandomSource** = () => `number`
Defined in: [packages/prng/src/uniform-int.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/uniform-int.ts#L4)
A source of random values in the half-open interval `[0, 1)`.
## Returns
[Section titled “Returns”](#returns)
`number`
# RandomSource64
> **RandomSource64** = () => `bigint`
Defined in: [packages/prng/src/uniform-int64.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/uniform-int64.ts#L4)
A source of unsigned 64-bit random values, such as `xoroshiro128StarStar(...).next`.
## Returns
[Section titled “Returns”](#returns)
`bigint`
# Xoroshiro128StarStarState
> **Xoroshiro128StarStarState** = readonly \[`state0`: `bigint`, `state1`: `bigint`]
Defined in: [packages/prng/src/xoroshiro128-star-star.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/xoroshiro128-star-star.ts#L22)
The two 64-bit words that initialize xoroshiro128\*\*.
# PRNG_ERROR_CODES
> `const` **PRNG_ERROR_CODES**: *typeof* [`PRNG_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/prng/variables/prng_invalid_input_error_codes/) = `PRNG_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/prng/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L15)
Every machine-readable error code emitted by `knotkit/prng`.
# PRNG_INVALID_INPUT_ERROR_CODES
> `const` **PRNG_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_BOUND"`, `"INVALID_SOURCE_VALUE"`, `"INVALID_STATE"`]
Defined in: [packages/prng/src/errors.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/prng/src/errors.ts#L12)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/prng`.
`INVALID_BOUND` marks a sampling bound outside the range a 32-bit draw can serve, `INVALID_SOURCE_VALUE` an injected random source returning a value outside `[0, 1)`, and `INVALID_STATE` a generator receiving a forbidden initial state.
# knotkit/rate-limit
## Classes
[Section titled “Classes”](#classes)
* [RateLimitInvalidInputError](/reference/knotkit/rate-limit/classes/ratelimitinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [TrackedAllowedDecision](/reference/knotkit/rate-limit/interfaces/trackedalloweddecision/)
* [UntrackedAllowedDecision](/reference/knotkit/rate-limit/interfaces/untrackedalloweddecision/)
* [RefusedDecision](/reference/knotkit/rate-limit/interfaces/refuseddecision/)
* [KeyedRateLimitTableOptions](/reference/knotkit/rate-limit/interfaces/keyedratelimittableoptions/)
* [KeyedRateLimitTable](/reference/knotkit/rate-limit/interfaces/keyedratelimittable/)
* [AllowedDecision](/reference/knotkit/rate-limit/interfaces/alloweddecision/)
* [DeniedDecision](/reference/knotkit/rate-limit/interfaces/denieddecision/)
* [NeverFitsDecision](/reference/knotkit/rate-limit/interfaces/neverfitsdecision/)
* [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/)
* [RateLimiterOptions](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
* [TokenBucketOptions](/reference/knotkit/rate-limit/interfaces/tokenbucketoptions/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [RateLimitInvalidInputErrorCode](/reference/knotkit/rate-limit/type-aliases/ratelimitinvalidinputerrorcode/)
* [RateLimitErrorCode](/reference/knotkit/rate-limit/type-aliases/ratelimiterrorcode/)
* [KeyedTableDecision](/reference/knotkit/rate-limit/type-aliases/keyedtabledecision/)
* [RateLimiterKind](/reference/knotkit/rate-limit/type-aliases/ratelimiterkind/)
* [CustomRateMeterKind](/reference/knotkit/rate-limit/type-aliases/customratemeterkind/)
* [RateLimitOutcome](/reference/knotkit/rate-limit/type-aliases/ratelimitoutcome/)
* [KeyedTableFullChoice](/reference/knotkit/rate-limit/type-aliases/keyedtablefullchoice/)
* [RateLimitDecision](/reference/knotkit/rate-limit/type-aliases/ratelimitdecision/)
* [RateMeterFactory](/reference/knotkit/rate-limit/type-aliases/ratemeterfactory/)
* [RateLimiterParametersByKind](/reference/knotkit/rate-limit/type-aliases/ratelimiterparametersbykind/)
* [RateLimiterFactory](/reference/knotkit/rate-limit/type-aliases/ratelimiterfactory/)
## Variables
[Section titled “Variables”](#variables)
* [RATE_LIMIT_INVALID_INPUT_ERROR_CODES](/reference/knotkit/rate-limit/variables/rate_limit_invalid_input_error_codes/)
* [RATE_LIMIT_ERROR_CODES](/reference/knotkit/rate-limit/variables/rate_limit_error_codes/)
* [\_\_RATE_LIMITER_LAYOUTS](/reference/knotkit/rate-limit/variables/rate_limiter_layouts/)
* [RATE_LIMITER_KINDS](/reference/knotkit/rate-limit/variables/rate_limiter_kinds/)
* [RATE_LIMIT_OUTCOMES](/reference/knotkit/rate-limit/variables/rate_limit_outcomes/)
* [KEYED_TABLE_FULL_CHOICES](/reference/knotkit/rate-limit/variables/keyed_table_full_choices/)
## Functions
[Section titled “Functions”](#functions)
* [fixedWindowRateLimiter](/reference/knotkit/rate-limit/functions/fixedwindowratelimiter/)
* [keyedRateLimitTable](/reference/knotkit/rate-limit/functions/keyedratelimittable/)
* [slidingWindowCounterRateLimiter](/reference/knotkit/rate-limit/functions/slidingwindowcounterratelimiter/)
* [slidingWindowLogRateLimiter](/reference/knotkit/rate-limit/functions/slidingwindowlogratelimiter/)
* [tokenBucketRateLimiter](/reference/knotkit/rate-limit/functions/tokenbucketratelimiter/)
# RateLimitInvalidInputError
Defined in: [packages/rate-limit/src/errors.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L29)
Thrown when a rate limit is constructed with parameters it cannot honour exactly, when a request carries a weight that is not a positive safe integer, or when the injected clock returns a number that is not finite.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`RateLimitInvalidInputErrorCode`](/reference/knotkit/rate-limit/type-aliases/ratelimitinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new RateLimitInvalidInputError**(`code`, `message`): `RateLimitInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"INVALID_CLOCK_READING"` | `"INVALID_WINDOW_DURATION"` | `"INVALID_REFILL_AMOUNT"` | `"INVALID_MAX_KEY_COUNT"` | `"INVALID_WHEN_FULL"` | `"PARAMETERS_TOO_LARGE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`RateLimitInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"INVALID_CLOCK_READING"` | `"INVALID_WINDOW_DURATION"` | `"INVALID_REFILL_AMOUNT"` | `"INVALID_MAX_KEY_COUNT"` | `"INVALID_WHEN_FULL"` | `"PARAMETERS_TOO_LARGE"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/rate-limit"`
Defined in: [packages/rate-limit/src/errors.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L30)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# fixedWindowRateLimiter
> **fixedWindowRateLimiter**(`options`): [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/fixed-window.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/fixed-window.ts#L58)
Create a [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/) that counts weight in fixed windows anchored at clock zero.
Windows sit on one grid, `windowIndex = Math.floor(now / windowDuration)`, so every client’s allowance resets at the same instant and the whole state is that index plus the weight spent in it. The promise is exactly what that grid can keep: a request is admitted whenever the window it lands in has room, so a client can be admitted up to `2 × capacity` within one trailing window of that width — a full capacity on each side of a boundary — while every window of the grid itself admits `capacity` and no more.
Choose it when the reset has to be a clock face everyone can predict — `capacity` per minute, per day — when the boundary burst is acceptable or cannot happen because traffic is paced, and when the memory per key has to stay at one index and one counter. Choose `slidingWindowLogRateLimiter` instead when the trailing window itself is the contract, and `slidingWindowCounterRateLimiter` when a smoothed estimate of it is enough for less memory than the log needs.
`peek` answers with the decision `take` would, and neither a `denied` nor a `never-fits` answer spends weight, so a caller can ask before it acts. `take` and `peek` read the injected clock, which the meter clamps at its highest reading, so a reading taken now is never below one this meter already saw.
`take`, `peek`, and `freshAt` run in O(1) time, and the meter holds O(1) state.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
The capacity, the width of the anchored window, and the clock every reading comes from.
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not a positive safe integer, `INVALID_WINDOW_DURATION` when `options.windowDuration` is not one, or `PARAMETERS_TOO_LARGE` when three times `capacity x windowDuration` would stop being exact.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` from `take` and `peek` when the weight is not a positive safe integer, and `INVALID_CLOCK_READING` from `take`, `peek`, and `freshAt` when the injected clock returns a number that is not finite.
## Example
[Section titled “Example”](#example)
```ts
const time = scriptedClock()
const meter = fixedWindowRateLimiter({ capacity: 2, windowDuration: 1_000, clock: time.clock })
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_000 }
time.advance(1_000)
meter.take(1) // { outcome: 'allowed' }
```
# keyedRateLimitTable
> **keyedRateLimitTable**<`K`>(`options`): [`KeyedRateLimitTable`](/reference/knotkit/rate-limit/interfaces/keyedratelimittable/)<`K`>
Defined in: [packages/rate-limit/src/keyed-table.ts:170](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L170)
Create a [KeyedRateLimitTable](/reference/knotkit/rate-limit/interfaces/keyedratelimittable/) over a caller-supplied meter factory.
Choose it when the server limits many clients and must survive a flood of new keys without growing with every client it has ever seen. Choose a single meter instead when there is one quota and no keys: a table for one key is a meter with extra steps.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`KeyedRateLimitTableOptions`](/reference/knotkit/rate-limit/interfaces/keyedratelimittableoptions/)
The key bound, the meter factory, the clock, and the table-full choice.
## Returns
[Section titled “Returns”](#returns)
[`KeyedRateLimitTable`](/reference/knotkit/rate-limit/interfaces/keyedratelimittable/)<`K`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_MAX_KEY_COUNT` when `maxKeyCount` is not a positive safe integer, or `INVALID_WHEN_FULL` when `whenFull` is neither `refuse` nor `allow-untracked`. A factory that rejects its own options throws its own package’s error from here, because the table builds one meter at construction to answer for keys it does not hold.
# slidingWindowCounterRateLimiter
> **slidingWindowCounterRateLimiter**(`options`): [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/sliding-window-counter.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/sliding-window-counter.ts#L65)
Create a [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/) that estimates a trailing window from the two anchored windows it overlaps.
The state is the current window’s spend and the previous window’s. A request fits when `previous × (windowDuration − elapsed) + (current + weight) × windowDuration` is within `capacity × windowDuration`, which counts the previous window as if its weight had been spread evenly over it and only the part still inside the trailing window mattered. That assumption is the whole economy of the kind: two counters and one index per key, where the log needs one buffered instant per unit of admitted weight.
The promise is therefore approximate, and it is stated as its worst case. With the previous window’s weight spread evenly, every trailing window of that width admits exactly `capacity`. With it clustered instead, the trailing window ending `elapsed` milliseconds into the current one can hold up to `capacity + previous × (elapsed / windowDuration)`, approaching `2 × capacity` as that window’s end comes near: the estimate has by then forgotten weight that a window of that width still counts.
Choose it when a smoothed throttle is enough — an API key’s requests per minute, a crawler’s pages per hour — and the caller would rather pay two counters per key than an exact scan. Choose `slidingWindowLogRateLimiter` when the trailing window has to be exact, and `fixedWindowRateLimiter` when a boundary burst up to twice the capacity has to be admitted at the lowest cost anyway.
`peek` answers with the decision `take` would, and neither a `denied` nor a `never-fits` answer spends weight, so a caller can ask before it acts. `take` and `peek` read the injected clock, which the meter clamps at its highest reading, so a reading taken now is never below one this meter already saw.
`take`, `peek`, and `freshAt` run in O(1) time, and the meter holds O(1) state.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
The capacity, the width of the anchored windows, and the clock every reading comes from.
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not a positive safe integer, `INVALID_WINDOW_DURATION` when `options.windowDuration` is not one, or `PARAMETERS_TOO_LARGE` when three times `capacity x windowDuration` would stop being exact.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` from `take` and `peek` when the weight is not a positive safe integer, and `INVALID_CLOCK_READING` from `take`, `peek`, and `freshAt` when the injected clock returns a number that is not finite.
## Example
[Section titled “Example”](#example)
```ts
const time = scriptedClock()
const meter = slidingWindowCounterRateLimiter({ capacity: 2, windowDuration: 1_000, clock: time.clock })
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_500 }
time.advance(1_500)
meter.take(1) // { outcome: 'allowed' }
```
# slidingWindowLogRateLimiter
> **slidingWindowLogRateLimiter**(`options`): [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/sliding-window-log.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/sliding-window-log.ts#L58)
Create a [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/) that keeps the exact instant and weight of every request still inside its trailing window.
The window is `(now - windowDuration, now]`: a request taken exactly one window behind `now` has already left it, and one taken a millisecond inside it has not. That makes the promise exact: a trailing window holds exactly the weight taken into it, so a window admits `capacity` worth of traffic in total and refuses the next unit, never one unit early. It makes `retryAfter` exact too — the oldest request whose expiry frees the missing weight names the millisecond the same take fits — so a client that waits and comes back is denied only while other traffic still holds the window. A weight above `capacity` never fits, whatever the window holds.
Choose it when the boundary itself is the contract, such as a billing quota or a throttle an adversary probes, and the traffic admitted per window is small. It is the only kind whose trailing-window promise is exact, and the price is one buffered instant per unit of admitted weight: because every weight is a positive integer and the kept weights sum to `capacity` at most, at most `capacity` instants are held.
`peek` answers with the decision `take` would, and neither a `denied` nor a `never-fits` answer changes state, so a caller can ask before it spends.
`take` and `peek` run in O(k) amortised time, where `k` counts the entries a prune removes plus, on a denial, the entries the exact retry scan walks over; `freshAt` is O(1).
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
The capacity, the width of the trailing window, and the clock every reading comes from.
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not a positive safe integer, `INVALID_WINDOW_DURATION` when `options.windowDuration` is not one, or `PARAMETERS_TOO_LARGE` when three times `capacity x windowDuration` would stop being exact.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` from `take` and `peek` when the weight is not a positive safe integer, and `INVALID_CLOCK_READING` from `take`, `peek`, and `freshAt` when the injected clock returns a number that is not finite.
## Example
[Section titled “Example”](#example)
```ts
const time = scriptedClock()
const meter = slidingWindowLogRateLimiter({ capacity: 2, windowDuration: 1_000, clock: time.clock })
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_000 }
time.advance(1_000)
meter.take(1) // { outcome: 'allowed' }
```
# tokenBucketRateLimiter
> **tokenBucketRateLimiter**(`options`): [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/token-bucket.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/token-bucket.ts#L107)
Create a [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/) that spends weight from a bucket and refills it at `refillAmount` per `windowDuration`, continuously rather than at a boundary.
The bucket holds `capacity` weight when full and regains `refillAmount` over any `windowDuration` of elapsed clock, so a steady stream settles at `refillAmount` per window while an idle client still finds `capacity` waiting. A client that idles and then bursts is throttled from its second unit on, where a `fixed-window` meter forgives the burst at each boundary and a `sliding-window-log` meter gives the weight back only as each request of the first burst ages out of the trailing window.
The promise about a trailing window is the one this kind can keep: it admits at most `capacity` plus what refills during that window, and never more than `capacity` at one instant, however long the client was idle before it. Under a monotonic clock its decisions and its `retryAfter` times are exactly the ones a two-number bucket makes, which holds a fractional token count and refills it continuously; this meter reaches them from a single arrival time, so it carries no fraction and cannot drift.
Choose it when the caller’s contract is a sustained rate rather than a calendar window: tokens per minute in an LLM gateway, requests per second to an upstream API, bytes per second per client. Choose `slidingWindowLogRateLimiter` when a trailing window has to admit exactly `capacity` weight, and `fixedWindowRateLimiter` when the reset has to land on a clock face every client can predict.
`peek` answers with the decision `take` would, and neither a `denied` nor a `never-fits` answer spends weight or moves the arrival time, so a caller can ask before it acts. `take` and `peek` read the injected clock, which the meter clamps at its highest reading, so a reading taken now is never below one this meter already saw.
`take`, `peek`, and `freshAt` run in O(1) time, and the meter holds O(1) state.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`TokenBucketOptions`](/reference/knotkit/rate-limit/interfaces/tokenbucketoptions/)
The capacity, the width of one refill window, the weight refilled over it, and the clock every reading comes from.
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `options.capacity` is not a positive safe integer, `INVALID_WINDOW_DURATION` when `options.windowDuration` is not one, `INVALID_REFILL_AMOUNT` when `options.refillAmount` is not one, or `PARAMETERS_TOO_LARGE` when three times `capacity x windowDuration` would stop being exact.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` from `take` and `peek` when the weight is not a positive safe integer, and `INVALID_CLOCK_READING` from `take`, `peek`, and `freshAt` when the injected clock returns a number that is not finite.
## Example
[Section titled “Example”](#example)
```ts
const time = scriptedClock()
const meter = tokenBucketRateLimiter({
capacity: 2,
windowDuration: 1_000,
refillAmount: 1,
clock: time.clock,
})
meter.take(2) // { outcome: 'allowed' }
meter.take(1) // { outcome: 'denied', retryAfter: 1_000 }
time.advance(1_000)
meter.take(1) // { outcome: 'allowed' }
```
# AllowedDecision
Defined in: [packages/rate-limit/src/rate-limit.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L44)
The request fits and has been spent.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"allowed"`
Defined in: [packages/rate-limit/src/rate-limit.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L45)
# DeniedDecision
Defined in: [packages/rate-limit/src/rate-limit.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L49)
The request does not fit yet.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"denied"`
Defined in: [packages/rate-limit/src/rate-limit.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L50)
***
### retryAfter
[Section titled “retryAfter”](#retryafter)
> `readonly` **retryAfter**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L55)
The least whole number of milliseconds after which the same request succeeds with no other traffic, never below `1`.
# KeyedRateLimitTable
Defined in: [packages/rate-limit/src/keyed-table.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L117)
A bounded table of rate-limit meters, one per client key.
The table owns three things a caller would otherwise write by hand. It clamps its clock once and builds every meter with that one reading, so a key it forgot and rebuilt sees the time the one it replaced would have seen. It tracks the instant each key’s meter becomes fresh, and forgets a key only at that instant, so forgetting never changes a later decision: a client that comes back after being dropped gets exactly the answer the meter the table dropped would have given. And when a new key arrives with no room and nothing forgettable, it applies the caller’s table-full choice instead of guessing.
Any object meeting [RateMeter](/reference/knotkit/rate-limit/interfaces/ratemeter/) works as the meter, so two limits per client — requests per minute plus tokens per minute — are one meter that peeks both and takes both only when both allow. The table reads a meter’s freshness report and trusts it: it cannot verify the report without running the caller’s algorithm again. A custom meter that reports fresh too early makes the table forget a key that was still in debt, which forgives its clients; the documentation of such a meter owes that sentence.
`take` and `peek` of a held key run in O(1) expected time plus the meter’s own. A `take` of a new key on a full table walks the held keys whose queued fresh instant has passed, O(log n) each, where n is the number of keys held.
## Example
[Section titled “Example”](#example)
```ts
const time = scriptedClock()
const table = keyedRateLimitTable({
maxKeyCount: 1_000,
whenFull: 'refuse',
clock: time.clock,
meter: (clock) => fixedWindowRateLimiter({ capacity: 10, windowDuration: 1_000, clock }),
})
table.take('client-a', 1) // { outcome: 'allowed', untracked: false }
```
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### K
[Section titled “K”](#k)
`K`
## Properties
[Section titled “Properties”](#properties)
### maxKeyCount
[Section titled “maxKeyCount”](#maxkeycount)
> `readonly` **maxKeyCount**: `number`
Defined in: [packages/rate-limit/src/keyed-table.ts:119](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L119)
The most keys the table holds meters for.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/rate-limit/src/keyed-table.ts:121](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L121)
Number of keys held, each with its own meter. O(1).
***
### take
[Section titled “take”](#take)
> `readonly` **take**: (`key`, `weight`) => [`KeyedTableDecision`](/reference/knotkit/rate-limit/type-aliases/keyedtabledecision/)
Defined in: [packages/rate-limit/src/keyed-table.ts:138](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L138)
Spend `weight` against the key’s meter, creating that meter when the table has room or can forget a fresh key.
A weight that can never fit is answered before the table considers its own key bound, so a table too full to track a key still tells the caller the request is impossible rather than admitting it untracked.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`K`
##### weight
[Section titled “weight”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`KeyedTableDecision`](/reference/knotkit/rate-limit/type-aliases/keyedtabledecision/)
The meter’s decision with `untracked: false`, a `refused` decision in `refuse` mode, or an allowed decision with `untracked: true` in `allow-untracked` mode.
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_WEIGHT` when `weight` is not a positive safe integer. With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number. The table records nothing for the request after either.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: (`key`, `weight`) => [`KeyedTableDecision`](/reference/knotkit/rate-limit/type-aliases/keyedtabledecision/)
Defined in: [packages/rate-limit/src/keyed-table.ts:151](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L151)
Return the decision [take](/reference/knotkit/rate-limit/interfaces/keyedratelimittable/#take) would return for the key, adding no key and spending nothing, and never report `refused` or `untracked`: a peek records nothing for any key, so the table’s own key bound does not enter it.
A key the table does not hold answers with what its own fresh meter would decide, which is the decision `take` would report if the table had room.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`K`
##### weight
[Section titled “weight”](#weight-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`KeyedTableDecision`](/reference/knotkit/rate-limit/type-aliases/keyedtabledecision/)
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` when `weight` is not a positive safe integer, or `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
# KeyedRateLimitTableOptions
Defined in: [packages/rate-limit/src/keyed-table.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L58)
The options a keyed table needs to bound itself and to build one meter per key.
## Properties
[Section titled “Properties”](#properties)
### maxKeyCount
[Section titled “maxKeyCount”](#maxkeycount)
> `readonly` **maxKeyCount**: `number`
Defined in: [packages/rate-limit/src/keyed-table.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L63)
The most keys the table holds meters for. A positive safe integer. It bounds the table’s memory; it is not a limit on traffic.
***
### meter
[Section titled “meter”](#meter)
> `readonly` **meter**: [`RateMeterFactory`](/reference/knotkit/rate-limit/type-aliases/ratemeterfactory/)
Defined in: [packages/rate-limit/src/keyed-table.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L69)
Build one meter for one key. The table calls it with its own clamped reading, so every meter it holds shares one highest reading, and with a built-in factory the meter clamps it again to no effect.
***
### clock
[Section titled “clock”](#clock)
> `readonly` **clock**: [`Clock`](/reference/knotkit/cache/type-aliases/clock/)
Defined in: [packages/rate-limit/src/keyed-table.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L71)
The time source every meter reads through. The table clamps it once, for all of them.
***
### whenFull
[Section titled “whenFull”](#whenfull)
> `readonly` **whenFull**: `"refuse"` | `"allow-untracked"`
Defined in: [packages/rate-limit/src/keyed-table.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L77)
What a request from a key the table cannot hold gets: `refuse`, or `allow-untracked`. Required, because neither answer is safe for every server.
# NeverFitsDecision
Defined in: [packages/rate-limit/src/rate-limit.ts:62](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L62)
The request can never fit: its weight exceeds the meter’s capacity, so no wait changes the answer.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"never-fits"`
Defined in: [packages/rate-limit/src/rate-limit.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L63)
# RateLimiterOptions
Defined in: [packages/rate-limit/src/rate-limit.ts:137](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L137)
The options every built-in rate limiter accepts, whatever its kind.
The record is the same for three of the four kinds, so a caller can switch algorithm by changing the factory alone. Quantities are exact: a construction whose largest intermediate product would exceed `Number.MAX_SAFE_INTEGER` is rejected rather than approximated.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`TokenBucketOptions`](/reference/knotkit/rate-limit/interfaces/tokenbucketoptions/)
## Properties
[Section titled “Properties”](#properties)
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L142)
The most weight one instant can admit from a fresh state. A positive safe integer.
***
### windowDuration
[Section titled “windowDuration”](#windowduration)
> `readonly` **windowDuration**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L147)
The width of the kind’s trailing window, in the milliseconds of [clock](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#clock). A positive safe integer.
***
### clock
[Section titled “clock”](#clock)
> `readonly` **clock**: [`Clock`](/reference/knotkit/cache/type-aliases/clock/)
Defined in: [packages/rate-limit/src/rate-limit.ts:149](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L149)
The time source the meter reads through, injected so a test replays every decision.
# RateMeter
Defined in: [packages/rate-limit/src/rate-limit.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L79)
A rate-limit algorithm’s state for one key.
The same contract serves the two built-in-and-custom cases: a factory here builds one, and any object a caller supplies that meets these members works in a keyed table.
`take` and `peek` answer the same question and differ only in whether the weight is spent. Neither changes state on a denial.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"custom"` | `"fixed-window"` | `"sliding-window-log"` | `"sliding-window-counter"` | `"token-bucket"`
Defined in: [packages/rate-limit/src/rate-limit.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L81)
The algorithm this meter runs: a built-in kind, or `'custom'` for a caller-supplied one.
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L86)
The most weight one instant can admit from a fresh state. It bounds a single request: a weight above it is `never-fits`, in every kind.
***
### take
[Section titled “take”](#take)
> `readonly` **take**: (`weight`) => [`RateLimitDecision`](/reference/knotkit/rate-limit/type-aliases/ratelimitdecision/)
Defined in: [packages/rate-limit/src/rate-limit.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L95)
Spend `weight` when the request is allowed, otherwise report why not.
#### Parameters
[Section titled “Parameters”](#parameters)
##### weight
[Section titled “weight”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
[`RateLimitDecision`](/reference/knotkit/rate-limit/type-aliases/ratelimitdecision/)
#### Throws
[Section titled “Throws”](#throws)
With code `INVALID_WEIGHT` when `weight` is not a positive safe integer, or `INVALID_CLOCK_READING` when the injected clock returns a non-finite number. The meter is unchanged after either.
***
### peek
[Section titled “peek”](#peek)
> `readonly` **peek**: (`weight`) => [`RateLimitDecision`](/reference/knotkit/rate-limit/type-aliases/ratelimitdecision/)
Defined in: [packages/rate-limit/src/rate-limit.ts:104](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L104)
Return the decision [take](/reference/knotkit/rate-limit/interfaces/ratemeter/#take) would return for `weight` without spending it.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### weight
[Section titled “weight”](#weight-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
[`RateLimitDecision`](/reference/knotkit/rate-limit/type-aliases/ratelimitdecision/)
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_WEIGHT` when `weight` is not a positive safe integer, or `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
***
### freshAt
[Section titled “freshAt”](#freshat)
> `readonly` **freshAt**: () => `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:117](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L117)
The instant, in whole milliseconds of the injected clock, at which this meter’s state equals a fresh one’s, so dropping it cannot change a later decision.
It never decreases: a later call returns an instant at or after the one an earlier call returned. A keyed table relies on that, and keeps the instant it read when it created a key as a lower bound on every later one.
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### Throws
[Section titled “Throws”](#throws-2)
With code `INVALID_CLOCK_READING` when the injected clock returns a non-finite number.
# RefusedDecision
Defined in: [packages/rate-limit/src/keyed-table.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L30)
The table is at its key bound with no meter it may forget, and the caller chose to refuse new keys.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"refused"`
Defined in: [packages/rate-limit/src/keyed-table.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L31)
# TokenBucketOptions
Defined in: [packages/rate-limit/src/rate-limit.ts:153](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L153)
The options a `token-bucket` accepts: [RateLimiterOptions](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/) plus the weight it regains.
## Extends
[Section titled “Extends”](#extends)
* [`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
## Properties
[Section titled “Properties”](#properties)
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L142)
The most weight one instant can admit from a fresh state. A positive safe integer.
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/).[`capacity`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#capacity)
***
### windowDuration
[Section titled “windowDuration”](#windowduration)
> `readonly` **windowDuration**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:147](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L147)
The width of the kind’s trailing window, in the milliseconds of [clock](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#clock). A positive safe integer.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/).[`windowDuration`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#windowduration)
***
### clock
[Section titled “clock”](#clock)
> `readonly` **clock**: [`Clock`](/reference/knotkit/cache/type-aliases/clock/)
Defined in: [packages/rate-limit/src/rate-limit.ts:149](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L149)
The time source the meter reads through, injected so a test replays every decision.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/).[`clock`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#clock)
***
### refillAmount
[Section titled “refillAmount”](#refillamount)
> `readonly` **refillAmount**: `number`
Defined in: [packages/rate-limit/src/rate-limit.ts:159](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L159)
The weight the bucket regains over one [RateLimiterOptions.windowDuration](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/#windowduration). A positive safe integer; a steady trickle of requests settles at one `refillAmount` per window.
# TrackedAllowedDecision
Defined in: [packages/rate-limit/src/keyed-table.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L16)
The request fits and its weight was spent on the key’s meter.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"allowed"`
Defined in: [packages/rate-limit/src/keyed-table.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L17)
***
### untracked
[Section titled “untracked”](#untracked)
> `readonly` **untracked**: `false`
Defined in: [packages/rate-limit/src/keyed-table.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L19)
`false`, because the key’s meter recorded the weight.
# UntrackedAllowedDecision
Defined in: [packages/rate-limit/src/keyed-table.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L23)
The request fits, but the table had no room for its key, so nothing recorded its weight.
## Properties
[Section titled “Properties”](#properties)
### outcome
[Section titled “outcome”](#outcome)
> `readonly` **outcome**: `"allowed"`
Defined in: [packages/rate-limit/src/keyed-table.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L24)
***
### untracked
[Section titled “untracked”](#untracked)
> `readonly` **untracked**: `true`
Defined in: [packages/rate-limit/src/keyed-table.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L26)
`true`, because the table admitted the request without tracking the key.
# CustomRateMeterKind
> **CustomRateMeterKind** = `"custom"`
Defined in: [packages/rate-limit/src/rate-limit.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L21)
The `kind` a caller-supplied meter reports.
Kept out of [RATE_LIMITER_KINDS](/reference/knotkit/rate-limit/variables/rate_limiter_kinds/) because no factory here builds it: a custom meter is the caller’s own object, and a table accepts it for the same reason it accepts a built-in one.
# KeyedTableDecision
> **KeyedTableDecision** = [`TrackedAllowedDecision`](/reference/knotkit/rate-limit/interfaces/trackedalloweddecision/) | [`UntrackedAllowedDecision`](/reference/knotkit/rate-limit/interfaces/untrackedalloweddecision/) | [`DeniedDecision`](/reference/knotkit/rate-limit/interfaces/denieddecision/) | [`NeverFitsDecision`](/reference/knotkit/rate-limit/interfaces/neverfitsdecision/) | [`RefusedDecision`](/reference/knotkit/rate-limit/interfaces/refuseddecision/)
Defined in: [packages/rate-limit/src/keyed-table.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/keyed-table.ts#L35)
One decision a keyed table returns: a meter’s decision, a refused one, or an untracked allowance.
# KeyedTableFullChoice
> **KeyedTableFullChoice** = *typeof* [`KEYED_TABLE_FULL_CHOICES`](/reference/knotkit/rate-limit/variables/keyed_table_full_choices/)\[`number`]
Defined in: [packages/rate-limit/src/rate-limit.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L41)
One of the behaviors [KEYED_TABLE_FULL_CHOICES](/reference/knotkit/rate-limit/variables/keyed_table_full_choices/) names.
# RateLimitDecision
> **RateLimitDecision** = [`AllowedDecision`](/reference/knotkit/rate-limit/interfaces/alloweddecision/) | [`DeniedDecision`](/reference/knotkit/rate-limit/interfaces/denieddecision/) | [`NeverFitsDecision`](/reference/knotkit/rate-limit/interfaces/neverfitsdecision/)
Defined in: [packages/rate-limit/src/rate-limit.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L67)
One decision a meter returns.
# RateLimiterFactory
> **RateLimiterFactory**<`Kind`> = (`options`) => [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/rate-limit.ts:171](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L171)
Build the meter of one kind, from that kind’s row of [RateLimiterParametersByKind](/reference/knotkit/rate-limit/type-aliases/ratelimiterparametersbykind/).
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* [`RateLimiterKind`](/reference/knotkit/rate-limit/type-aliases/ratelimiterkind/) = [`RateLimiterKind`](/reference/knotkit/rate-limit/type-aliases/ratelimiterkind/)
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`RateLimiterParametersByKind`](/reference/knotkit/rate-limit/type-aliases/ratelimiterparametersbykind/)\[`Kind`]
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
# RateLimiterKind
> **RateLimiterKind** = *typeof* [`RATE_LIMITER_KINDS`](/reference/knotkit/rate-limit/variables/rate_limiter_kinds/)\[`number`]
Defined in: [packages/rate-limit/src/rate-limit.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L12)
One of the algorithms [RATE_LIMITER_KINDS](/reference/knotkit/rate-limit/variables/rate_limiter_kinds/) names.
# RateLimiterParametersByKind
> **RateLimiterParametersByKind** = `object`
Defined in: [packages/rate-limit/src/rate-limit.ts:163](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L163)
One options row per kind, so a generic caller keeps the kind and its options related.
## Properties
[Section titled “Properties”](#properties)
### fixed-window
[Section titled “fixed-window”](#fixed-window)
> `readonly` **fixed-window**: [`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
Defined in: [packages/rate-limit/src/rate-limit.ts:164](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L164)
***
### sliding-window-log
[Section titled “sliding-window-log”](#sliding-window-log)
> `readonly` **sliding-window-log**: [`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
Defined in: [packages/rate-limit/src/rate-limit.ts:165](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L165)
***
### sliding-window-counter
[Section titled “sliding-window-counter”](#sliding-window-counter)
> `readonly` **sliding-window-counter**: [`RateLimiterOptions`](/reference/knotkit/rate-limit/interfaces/ratelimiteroptions/)
Defined in: [packages/rate-limit/src/rate-limit.ts:166](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L166)
***
### token-bucket
[Section titled “token-bucket”](#token-bucket)
> `readonly` **token-bucket**: [`TokenBucketOptions`](/reference/knotkit/rate-limit/interfaces/tokenbucketoptions/)
Defined in: [packages/rate-limit/src/rate-limit.ts:167](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L167)
# RateLimitErrorCode
> **RateLimitErrorCode** = [`RateLimitInvalidInputErrorCode`](/reference/knotkit/rate-limit/type-aliases/ratelimitinvalidinputerrorcode/)
Defined in: [packages/rate-limit/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L22)
A machine-readable error code emitted by `knotkit/rate-limit`.
# RateLimitInvalidInputErrorCode
> **RateLimitInvalidInputErrorCode** = *typeof* [`RATE_LIMIT_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/rate-limit/variables/rate_limit_invalid_input_error_codes/)\[`number`]
Defined in: [packages/rate-limit/src/errors.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L19)
A machine-readable invalid-input code emitted by `knotkit/rate-limit`.
# RateLimitOutcome
> **RateLimitOutcome** = *typeof* [`RATE_LIMIT_OUTCOMES`](/reference/knotkit/rate-limit/variables/rate_limit_outcomes/)\[`number`]
Defined in: [packages/rate-limit/src/rate-limit.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L32)
One of the outcomes [RATE_LIMIT_OUTCOMES](/reference/knotkit/rate-limit/variables/rate_limit_outcomes/) names.
# RateMeterFactory
> **RateMeterFactory** = (`clock`) => [`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
Defined in: [packages/rate-limit/src/rate-limit.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L127)
Build a meter over the reading its owner supplies.
A keyed table passes its own clamped reading, so every meter it holds shares one highest reading; a standalone factory clamps the caller’s clock itself. Either way the meter reads only through the function it was given.
## Parameters
[Section titled “Parameters”](#parameters)
### clock
[Section titled “clock”](#clock)
[`Clock`](/reference/knotkit/cache/type-aliases/clock/)
## Returns
[Section titled “Returns”](#returns)
[`RateMeter`](/reference/knotkit/rate-limit/interfaces/ratemeter/)
# KEYED_TABLE_FULL_CHOICES
> `const` **KEYED_TABLE_FULL_CHOICES**: readonly \[`"refuse"`, `"allow-untracked"`]
Defined in: [packages/rate-limit/src/rate-limit.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L35)
The two behaviors a keyed table applies to a new key it has no room for.
# RATE_LIMIT_ERROR_CODES
> `const` **RATE_LIMIT_ERROR_CODES**: *typeof* [`RATE_LIMIT_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/rate-limit/variables/rate_limit_invalid_input_error_codes/) = `RATE_LIMIT_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/rate-limit/src/errors.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L16)
Every machine-readable error code emitted by `knotkit/rate-limit`.
# RATE_LIMIT_INVALID_INPUT_ERROR_CODES
> `const` **RATE_LIMIT_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_CAPACITY"`, `"INVALID_WINDOW_DURATION"`, `"INVALID_REFILL_AMOUNT"`, `"INVALID_WEIGHT"`, `"INVALID_MAX_KEY_COUNT"`, `"INVALID_WHEN_FULL"`, `"INVALID_CLOCK_READING"`, `"PARAMETERS_TOO_LARGE"`]
Defined in: [packages/rate-limit/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/rate-limit`.
# RATE_LIMIT_OUTCOMES
> `const` **RATE_LIMIT_OUTCOMES**: readonly \[`"allowed"`, `"denied"`, `"never-fits"`, `"refused"`]
Defined in: [packages/rate-limit/src/rate-limit.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L24)
Every outcome a rate limit reports: the three a meter returns, and the one only a keyed table does.
# RATE_LIMITER_KINDS
> `const` **RATE_LIMITER_KINDS**: readonly \[`"fixed-window"`, `"sliding-window-log"`, `"sliding-window-counter"`, `"token-bucket"`]
Defined in: [packages/rate-limit/src/rate-limit.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/rate-limit.ts#L4)
The four algorithms a rate limit ships, each a different promise about a trailing window.
# __RATE_LIMITER_LAYOUTS
> `const` **\_\_RATE_LIMITER_LAYOUTS**: `Readonly`<`{ [Kind in RateLimiterKind]: RateLimiterFactory }`>
Defined in: [packages/rate-limit/src/layouts.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/rate-limit/src/layouts.ts#L14)
Every rate-limiting algorithm, keyed by the `kind` a meter built from it reports.
Each row takes that kind’s options, so `__RATE_LIMITER_LAYOUTS[kind](preset)` builds any meter.
# knotkit/sampling
## Classes
[Section titled “Classes”](#classes)
* [SamplingInvalidInputError](/reference/knotkit/sampling/classes/samplinginvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [ReservoirSampler](/reference/knotkit/sampling/interfaces/reservoirsampler/)
* [ConstrainedPairOptions](/reference/knotkit/sampling/interfaces/constrainedpairoptions/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [SamplingInvalidInputErrorCode](/reference/knotkit/sampling/type-aliases/samplinginvalidinputerrorcode/)
* [SamplingErrorCode](/reference/knotkit/sampling/type-aliases/samplingerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [SAMPLING_INVALID_INPUT_ERROR_CODES](/reference/knotkit/sampling/variables/sampling_invalid_input_error_codes/)
* [SAMPLING_ERROR_CODES](/reference/knotkit/sampling/variables/sampling_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [reservoirSampler](/reference/knotkit/sampling/functions/reservoirsampler/)
* [sampleIndices](/reference/knotkit/sampling/functions/sampleindices/)
* [samplePair](/reference/knotkit/sampling/functions/samplepair/)
* [sampleConstrainedPair](/reference/knotkit/sampling/functions/sampleconstrainedpair/)
* [shuffled](/reference/knotkit/sampling/functions/shuffled/)
* [weightedChoice](/reference/knotkit/sampling/functions/weightedchoice/)
* [weightedSampleFromLogWeights](/reference/knotkit/sampling/functions/weightedsamplefromlogweights/)
* [weightedSample](/reference/knotkit/sampling/functions/weightedsample/)
# SamplingInvalidInputError
Defined in: [packages/sampling/src/errors.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L27)
Thrown when sampling inputs cannot describe the requested distribution.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`SamplingInvalidInputErrorCode`](/reference/knotkit/sampling/type-aliases/samplinginvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new SamplingInvalidInputError**(`code`, `message`): `SamplingInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_RANGE"` | `"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"INVALID_POPULATION_SIZE"` | `"INVALID_SAMPLE_SIZE"` | `"INVALID_GAP"` | `"INVALID_LOG_WEIGHT"` | `"ZERO_TOTAL_WEIGHT"` | `"INSUFFICIENT_POSITIVE_WEIGHT"` | `"STREAM_LIMIT_EXCEEDED"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`SamplingInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_RANGE"` | `"INVALID_CAPACITY"` | `"INVALID_WEIGHT"` | `"INVALID_POPULATION_SIZE"` | `"INVALID_SAMPLE_SIZE"` | `"INVALID_GAP"` | `"INVALID_LOG_WEIGHT"` | `"ZERO_TOTAL_WEIGHT"` | `"INSUFFICIENT_POSITIVE_WEIGHT"` | `"STREAM_LIMIT_EXCEEDED"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/sampling"`
Defined in: [packages/sampling/src/errors.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L28)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# reservoirSampler
> **reservoirSampler**<`T`>(`random`, `capacity`): [`ReservoirSampler`](/reference/knotkit/sampling/interfaces/reservoirsampler/)<`T`>
Defined in: [packages/sampling/src/reservoir-sampler.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L93)
Create a uniform reservoir sampler over a stream of unknown length.
Vitter’s Algorithm R: the first `capacity` values fill the reservoir, and the `n`-th value after that replaces a uniformly drawn slot with probability `capacity / n`. One draw per value past the reservoir keeps every observed value at inclusion probability `capacity / n` after each one.
The sampler accepts at most 2^32 values, the same population bound `sampleIndices` accepts, because the slot draw for the `n`-th value asks `uniformInt` for a bound of `n`.
Replaying the same values against the same source state reproduces every replacement and every snapshot.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
Function returning values in `[0, 1)`.
### capacity
[Section titled “capacity”](#capacity)
`number`
The maximum number of retained values, from 0 through 2^32 - 1.
## Returns
[Section titled “Returns”](#returns)
[`ReservoirSampler`](/reference/knotkit/sampling/interfaces/reservoirsampler/)<`T`>
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_CAPACITY` when `capacity` is not a safe integer in `0..2^32 - 1`. Validation happens before the source is ever called.
# sampleConstrainedPair
> **sampleConstrainedPair**(`random`, `options`): readonly \[`number`, `number`]
Defined in: [packages/sampling/src/sample-pair.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L54)
Sample uniformly from ascending integer pairs whose gap is in the inclusive interval `[minimumGap, maximumGap]`.
Valid pairs are ranked by increasing gap and then increasing first index. Rank lookup takes O(log(maximumGap - minimumGap + 1)) time and O(1) auxiliary space. The options object is not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### options
[Section titled “options”](#options)
[`ConstrainedPairOptions`](/reference/knotkit/sampling/interfaces/constrainedpairoptions/)
## Returns
[Section titled “Returns”](#returns)
readonly \[`number`, `number`]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_RANGE` when bounds do not describe a supported range or the range contains more than 2^32 valid pairs, or `INVALID_GAP` when the gap interval is invalid for the range.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# sampleIndices
> **sampleIndices**(`random`, `populationSize`, `sampleSize`): readonly `number`\[]
Defined in: [packages/sampling/src/sample-indices.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-indices.ts#L17)
Sample a uniform subset of `0..populationSize - 1` in ascending order.
Floyd’s algorithm uses O(sampleSize) expected auxiliary space, followed by an O(sampleSize log sampleSize) canonical sort. The inputs are not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### populationSize
[Section titled “populationSize”](#populationsize)
`number`
### sampleSize
[Section titled “sampleSize”](#samplesize)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_POPULATION_SIZE` when `populationSize` is not a safe integer in `0..2^32`, or `INVALID_SAMPLE_SIZE` when `sampleSize` is not representable or exceeds the population.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# samplePair
> **samplePair**(`random`, `lowerBound`, `upperExclusive`): readonly \[`number`, `number`]
Defined in: [packages/sampling/src/sample-pair.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L23)
Sample an ascending pair of distinct integers in `[lowerBound, upperExclusive)`.
Runs in O(1) time and auxiliary space and does not mutate its inputs.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
`number`
### upperExclusive
[Section titled “upperExclusive”](#upperexclusive)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly \[`number`, `number`]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_RANGE` when the bounds are not safe integers spanning between 2 and 2^32 values.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# shuffled
> **shuffled**<`T`>(`random`, `values`): readonly `T`\[]
Defined in: [packages/sampling/src/shuffle.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/shuffle.ts#L12)
Return a uniformly shuffled copy of `values` using Fisher-Yates.
Runs in O(values.length) time and uses O(values.length) space for the copy. The input is never mutated.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### values
[Section titled “values”](#values)
readonly `T`\[]
## Returns
[Section titled “Returns”](#returns)
readonly `T`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# weightedChoice
> **weightedChoice**(`random`, `weights`): `number`
Defined in: [packages/sampling/src/weighted-choice.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/weighted-choice.ts#L17)
Sample one index proportionally to its finite non-negative weight.
Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the largest weight keeps the cumulative sum finite without changing the distribution. The weights are not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### weights
[Section titled “weights”](#weights)
readonly `number`\[]
## Returns
[Section titled “Returns”](#returns)
`number`
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_WEIGHT` when a weight is negative or non-finite, or `ZERO_TOTAL_WEIGHT` when the array is empty or contains no positive weight.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# weightedSample
> **weightedSample**(`random`, `weights`, `sampleSize`): readonly `number`\[]
Defined in: [packages/sampling/src/weighted-sample.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/weighted-sample.ts#L21)
Sample weighted indices without replacement in ascending source order.
Uses Efraimidis-Spirakis keys ranked in log space and a bounded min priority queue, taking O(weights.length log sampleSize) time and O(sampleSize) auxiliary space. Zero-weight entries are ineligible, equal keys prefer the lower source index, and the weights are not mutated. Ranking in log space keeps subnormal weights separable rather than tying them all together.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### weights
[Section titled “weights”](#weights)
readonly `number`\[]
### sampleSize
[Section titled “sampleSize”](#samplesize)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_WEIGHT` when a weight is negative or non-finite, `INVALID_SAMPLE_SIZE` when `sampleSize` is not a valid array size, or `INSUFFICIENT_POSITIVE_WEIGHT` when too few weights are positive.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# weightedSampleFromLogWeights
> **weightedSampleFromLogWeights**(`random`, `logWeights`, `sampleSize`): readonly `number`\[]
Defined in: [packages/sampling/src/weighted-sample-from-log-weights.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/weighted-sample-from-log-weights.ts#L30)
Sample indices without replacement from log-weights, in ascending source order.
Each entry is the natural logarithm of a non-negative weight, so `weightedSampleFromLogWeights(random, weights.map(Math.log), sampleSize)` returns exactly what `weightedSample` returns for the same finite weights and source state. Skipping the round trip through `Math.exp` keeps an entry eligible and separable however small its weight is: a log-weight of `-800` is a valid input even though `Math.exp(-800)` is zero.
`-Infinity` marks an ineligible entry, mirroring a zero weight exactly: it is skipped before its draw and can never be returned. Every other eligible entry consumes exactly one draw, in source order, and a `sampleSize` of zero consumes none. Uses Efraimidis-Spirakis keys and a bounded min priority queue, taking O(logWeights.length log sampleSize) time and O(sampleSize) auxiliary space. Equal keys prefer the lower source index, and the log-weights are not mutated.
## Parameters
[Section titled “Parameters”](#parameters)
### random
[Section titled “random”](#random)
[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)
### logWeights
[Section titled “logWeights”](#logweights)
readonly `number`\[]
### sampleSize
[Section titled “sampleSize”](#samplesize)
`number`
## Returns
[Section titled “Returns”](#returns)
readonly `number`\[]
## Throws
[Section titled “Throws”](#throws)
With code `INVALID_LOG_WEIGHT` when a log-weight is `NaN` or `+Infinity`, `INVALID_SAMPLE_SIZE` when `sampleSize` is not a valid array size, or `INSUFFICIENT_POSITIVE_WEIGHT` when too few log-weights are finite.
## Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
# ConstrainedPairOptions
Defined in: [packages/sampling/src/sample-pair.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L6)
Bounds and inclusive gap limits for [sampleConstrainedPair](/reference/knotkit/sampling/functions/sampleconstrainedpair/).
## Properties
[Section titled “Properties”](#properties)
### lowerBound
[Section titled “lowerBound”](#lowerbound)
> `readonly` **lowerBound**: `number`
Defined in: [packages/sampling/src/sample-pair.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L7)
***
### upperExclusive
[Section titled “upperExclusive”](#upperexclusive)
> `readonly` **upperExclusive**: `number`
Defined in: [packages/sampling/src/sample-pair.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L8)
***
### minimumGap
[Section titled “minimumGap”](#minimumgap)
> `readonly` **minimumGap**: `number`
Defined in: [packages/sampling/src/sample-pair.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L9)
***
### maximumGap
[Section titled “maximumGap”](#maximumgap)
> `readonly` **maximumGap**: `number`
Defined in: [packages/sampling/src/sample-pair.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/sample-pair.ts#L10)
# ReservoirSampler
Defined in: [packages/sampling/src/reservoir-sampler.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L19)
A bounded uniform sample of a stream whose length is not known in advance.
The sampler retains at most `capacity` values and never keeps the values it has rejected, so its memory is O(capacity) however long the stream runs. After `n >= capacity` observed values, every one of them is retained with probability `capacity / n`.
The type parameter is invariant: the sampler both consumes `T` through `add` and produces `T` through `snapshot`, so `ReservoirSampler` must not be assignable to `ReservoirSampler` — that would allow adding a `Cat`. `add` and `addAll` are declared in property syntax on purpose, because method-syntax parameters compare bivariantly and would defeat that.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"reservoir-sampler"`
Defined in: [packages/sampling/src/reservoir-sampler.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L21)
Serializable identifier for this sampler implementation.
***
### capacity
[Section titled “capacity”](#capacity)
> `readonly` **capacity**: `number`
Defined in: [packages/sampling/src/reservoir-sampler.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L24)
The maximum number of retained values.
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`value`) => `void`
Defined in: [packages/sampling/src/reservoir-sampler.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L41)
Observe one stream value, retaining it with probability `capacity / seenCount()` once the reservoir has filled. O(1) amortized.
Consumes no draw for the first `capacity` values and exactly one `uniformInt` draw for every value after them, including any rejection draws `uniformInt` performs internally. A sampler of capacity zero never draws. When this throws, the value was not observed: `seenCount()` and `snapshot()` are left as they were.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`T`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With code `STREAM_LIMIT_EXCEEDED` when the sampler has already observed 2^32 values.
#### Throws
[Section titled “Throws”](#throws-1)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
***
### addAll
[Section titled “addAll”](#addall)
> `readonly` **addAll**: (`values`) => `void`
Defined in: [packages/sampling/src/reservoir-sampler.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L54)
Observe every value of an iterable in order, as repeated `add` calls.
When this throws mid-iteration, the values before the failing one were observed and the failing one was not.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### values
[Section titled “values”](#values)
`Iterable`<`T`>
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws-2)
With code `STREAM_LIMIT_EXCEEDED` when the sampler reaches 2^32 observed values.
#### Throws
[Section titled “Throws”](#throws-3)
With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
## Methods
[Section titled “Methods”](#methods)
### seenCount()
[Section titled “seenCount()”](#seencount)
> **seenCount**(): `number`
Defined in: [packages/sampling/src/reservoir-sampler.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L57)
The number of values observed so far. O(1).
#### Returns
[Section titled “Returns”](#returns-2)
`number`
***
### snapshot()
[Section titled “snapshot()”](#snapshot)
> **snapshot**(): readonly `T`\[]
Defined in: [packages/sampling/src/reservoir-sampler.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/reservoir-sampler.ts#L68)
A fresh copy of the retained values in slot order. O(capacity).
Slot order is deterministic under replay, but it is neither stream order nor a uniformly random order; pass the result through `shuffled` when a random order matters. Values are held by reference and never cloned. Consumes no draw and leaves the sampler unchanged, and mutating the returned array does not affect it.
#### Returns
[Section titled “Returns”](#returns-3)
readonly `T`\[]
# SamplingErrorCode
> **SamplingErrorCode** = [`SamplingInvalidInputErrorCode`](/reference/knotkit/sampling/type-aliases/samplinginvalidinputerrorcode/)
Defined in: [packages/sampling/src/errors.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L24)
A machine-readable error code emitted by `knotkit/sampling`.
# SamplingInvalidInputErrorCode
> **SamplingInvalidInputErrorCode** = *typeof* [`SAMPLING_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/sampling/variables/sampling_invalid_input_error_codes/)\[`number`]
Defined in: [packages/sampling/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L21)
A machine-readable invalid-input code emitted by `knotkit/sampling`.
# SAMPLING_ERROR_CODES
> `const` **SAMPLING_ERROR_CODES**: *typeof* [`SAMPLING_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/sampling/variables/sampling_invalid_input_error_codes/) = `SAMPLING_INVALID_INPUT_ERROR_CODES`
Defined in: [packages/sampling/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L18)
Every machine-readable error code emitted by `knotkit/sampling`.
# SAMPLING_INVALID_INPUT_ERROR_CODES
> `const` **SAMPLING_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_POPULATION_SIZE"`, `"INVALID_SAMPLE_SIZE"`, `"INVALID_RANGE"`, `"INVALID_GAP"`, `"INVALID_WEIGHT"`, `"INVALID_LOG_WEIGHT"`, `"ZERO_TOTAL_WEIGHT"`, `"INSUFFICIENT_POSITIVE_WEIGHT"`, `"INVALID_CAPACITY"`, `"STREAM_LIMIT_EXCEEDED"`]
Defined in: [packages/sampling/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/sampling`.
# knotkit/scalar-sketch
## Classes
[Section titled “Classes”](#classes)
* [ScalarSketchInvalidInputError](/reference/knotkit/scalar-sketch/classes/scalarsketchinvalidinputerror/)
* [ScalarSketchParseError](/reference/knotkit/scalar-sketch/classes/scalarsketchparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [CountMinSketchOptions](/reference/knotkit/scalar-sketch/interfaces/countminsketchoptions/)
* [CountMinSketchMetadata](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/)
* [StringCountMinSketch](/reference/knotkit/scalar-sketch/interfaces/stringcountminsketch/)
* [BytesCountMinSketch](/reference/knotkit/scalar-sketch/interfaces/bytescountminsketch/)
* [Uint32CountMinSketch](/reference/knotkit/scalar-sketch/interfaces/uint32countminsketch/)
* [Uint64CountMinSketch](/reference/knotkit/scalar-sketch/interfaces/uint64countminsketch/)
* [HyperLogLogOptions](/reference/knotkit/scalar-sketch/interfaces/hyperloglogoptions/)
* [HyperLogLogMetadata](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/)
* [StringHyperLogLog](/reference/knotkit/scalar-sketch/interfaces/stringhyperloglog/)
* [BytesHyperLogLog](/reference/knotkit/scalar-sketch/interfaces/byteshyperloglog/)
* [Uint32HyperLogLog](/reference/knotkit/scalar-sketch/interfaces/uint32hyperloglog/)
* [Uint64HyperLogLog](/reference/knotkit/scalar-sketch/interfaces/uint64hyperloglog/)
* [SplitBlockBloomCompatibilityConfig](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomcompatibilityconfig/)
* [HyperLogLogCompatibilityConfig](/reference/knotkit/scalar-sketch/interfaces/hyperloglogcompatibilityconfig/)
* [CountMinCompatibilityConfig](/reference/knotkit/scalar-sketch/interfaces/countmincompatibilityconfig/)
* [MinHashCompatibilityConfig](/reference/knotkit/scalar-sketch/interfaces/minhashcompatibilityconfig/)
* [SketchCompatibilityConfigByKind](/reference/knotkit/scalar-sketch/interfaces/sketchcompatibilityconfigbykind/)
* [MinHashOptions](/reference/knotkit/scalar-sketch/interfaces/minhashoptions/)
* [MinHashMetadata](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/)
* [StringMinHash](/reference/knotkit/scalar-sketch/interfaces/stringminhash/)
* [BytesMinHash](/reference/knotkit/scalar-sketch/interfaces/bytesminhash/)
* [Uint32MinHash](/reference/knotkit/scalar-sketch/interfaces/uint32minhash/)
* [Uint64MinHash](/reference/knotkit/scalar-sketch/interfaces/uint64minhash/)
* [SplitBlockBloomFilterOptions](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfilteroptions/)
* [SplitBlockBloomFilterMetadata](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/)
* [StringSplitBlockBloomFilter](/reference/knotkit/scalar-sketch/interfaces/stringsplitblockbloomfilter/)
* [BytesSplitBlockBloomFilter](/reference/knotkit/scalar-sketch/interfaces/bytessplitblockbloomfilter/)
* [Uint32SplitBlockBloomFilter](/reference/knotkit/scalar-sketch/interfaces/uint32splitblockbloomfilter/)
* [Uint64SplitBlockBloomFilter](/reference/knotkit/scalar-sketch/interfaces/uint64splitblockbloomfilter/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [ScalarSketchInvalidInputErrorCode](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchinvalidinputerrorcode/)
* [ScalarSketchParseErrorCode](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchparseerrorcode/)
* [ScalarSketchErrorCode](/reference/knotkit/scalar-sketch/type-aliases/scalarsketcherrorcode/)
* [SketchKind](/reference/knotkit/scalar-sketch/type-aliases/sketchkind/)
* [ScalarKind](/reference/knotkit/scalar-sketch/type-aliases/scalarkind/)
* [SeedScheduleIdentity](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
* [SketchCompatibilityIdentity](/reference/knotkit/scalar-sketch/type-aliases/sketchcompatibilityidentity/)
* [ScalarSketch](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
## Variables
[Section titled “Variables”](#variables)
* [SCALAR_SKETCH_INVALID_INPUT_ERROR_CODES](/reference/knotkit/scalar-sketch/variables/scalar_sketch_invalid_input_error_codes/)
* [SCALAR_SKETCH_PARSE_ERROR_CODES](/reference/knotkit/scalar-sketch/variables/scalar_sketch_parse_error_codes/)
* [SCALAR_SKETCH_ERROR_CODES](/reference/knotkit/scalar-sketch/variables/scalar_sketch_error_codes/)
* [SKETCH_KINDS](/reference/knotkit/scalar-sketch/variables/sketch_kinds/)
* [SCALAR_KINDS](/reference/knotkit/scalar-sketch/variables/scalar_kinds/)
* [SCALAR_SKETCH_WIRE_VERSION](/reference/knotkit/scalar-sketch/variables/scalar_sketch_wire_version/)
## Functions
[Section titled “Functions”](#functions)
* [stringCountMinSketch](/reference/knotkit/scalar-sketch/functions/stringcountminsketch/)
* [bytesCountMinSketch](/reference/knotkit/scalar-sketch/functions/bytescountminsketch/)
* [uint32CountMinSketch](/reference/knotkit/scalar-sketch/functions/uint32countminsketch/)
* [uint64CountMinSketch](/reference/knotkit/scalar-sketch/functions/uint64countminsketch/)
* [stringHyperLogLog](/reference/knotkit/scalar-sketch/functions/stringhyperloglog/)
* [bytesHyperLogLog](/reference/knotkit/scalar-sketch/functions/byteshyperloglog/)
* [uint32HyperLogLog](/reference/knotkit/scalar-sketch/functions/uint32hyperloglog/)
* [uint64HyperLogLog](/reference/knotkit/scalar-sketch/functions/uint64hyperloglog/)
* [stringMinHash](/reference/knotkit/scalar-sketch/functions/stringminhash/)
* [bytesMinHash](/reference/knotkit/scalar-sketch/functions/bytesminhash/)
* [uint32MinHash](/reference/knotkit/scalar-sketch/functions/uint32minhash/)
* [uint64MinHash](/reference/knotkit/scalar-sketch/functions/uint64minhash/)
* [stringSplitBlockBloomFilter](/reference/knotkit/scalar-sketch/functions/stringsplitblockbloomfilter/)
* [bytesSplitBlockBloomFilter](/reference/knotkit/scalar-sketch/functions/bytessplitblockbloomfilter/)
* [uint32SplitBlockBloomFilter](/reference/knotkit/scalar-sketch/functions/uint32splitblockbloomfilter/)
* [uint64SplitBlockBloomFilter](/reference/knotkit/scalar-sketch/functions/uint64splitblockbloomfilter/)
# ScalarSketchInvalidInputError
Defined in: [packages/scalar-sketch/src/errors.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L55)
Thrown for invalid options, foreign sketches, incompatibility, capacity, or arithmetic failure.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`ScalarSketchInvalidInputErrorCode`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new ScalarSketchInvalidInputError**(`code`, `message`): `ScalarSketchInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_WEIGHT"` | `"INVALID_DIMENSION"` | `"INVALID_PROBABILITY"` | `"FOREIGN_STRUCTURE"` | `"INVALID_PRECISION"` | `"INVALID_SIGNATURE_SIZE"` | `"STATE_TOO_LARGE"` | `"WRONG_FAMILY"` | `"INCOMPATIBLE_SKETCH"` | `"INVALID_REDUCTION"` | `"CAPACITY_EXCEEDED"` | `"COUNTER_OVERFLOW"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`ScalarSketchInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_WEIGHT"` | `"INVALID_DIMENSION"` | `"INVALID_PROBABILITY"` | `"FOREIGN_STRUCTURE"` | `"INVALID_PRECISION"` | `"INVALID_SIGNATURE_SIZE"` | `"STATE_TOO_LARGE"` | `"WRONG_FAMILY"` | `"INCOMPATIBLE_SKETCH"` | `"INVALID_REDUCTION"` | `"CAPACITY_EXCEEDED"` | `"COUNTER_OVERFLOW"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/scalar-sketch"`
Defined in: [packages/scalar-sketch/src/errors.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L56)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# ScalarSketchParseError
Defined in: [packages/scalar-sketch/src/errors.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L60)
Thrown when a scalar-sketch persistence envelope or family state is invalid.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`ScalarSketchParseErrorCode`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new ScalarSketchParseError**(`code`, `message`): `ScalarSketchParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_SHAPE"` | `"INVALID_STATE"` | `"STATE_TOO_LARGE"` | `"INVALID_ENVELOPE"` | `"UNKNOWN_SCALAR_KIND"` | `"UNSUPPORTED_WIRE_VERSION"` | `"UNSUPPORTED_PRODUCER_VERSION"` | `"UNSUPPORTED_SCHEDULE"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`ScalarSketchParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_SHAPE"` | `"INVALID_STATE"` | `"STATE_TOO_LARGE"` | `"INVALID_ENVELOPE"` | `"UNKNOWN_SCALAR_KIND"` | `"UNSUPPORTED_WIRE_VERSION"` | `"UNSUPPORTED_PRODUCER_VERSION"` | `"UNSUPPORTED_SCHEDULE"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/scalar-sketch"`
Defined in: [packages/scalar-sketch/src/errors.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L61)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# bytesCountMinSketch
> **bytesCountMinSketch**(`options?`): [`BytesCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/bytescountminsketch/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L118)
Create a byte-array-specialized Count-Min sketch.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`CountMinSketchOptions`](/reference/knotkit/scalar-sketch/interfaces/countminsketchoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`BytesCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/bytescountminsketch/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_DIMENSION`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# bytesHyperLogLog
> **bytesHyperLogLog**(`options?`): [`BytesHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/byteshyperloglog/)
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:162](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L162)
Create a byte-array-specialized HyperLogLog.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`HyperLogLogOptions`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`BytesHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/byteshyperloglog/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PRECISION` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# bytesMinHash
> **bytesMinHash**(`options?`): [`BytesMinHash`](/reference/knotkit/scalar-sketch/interfaces/bytesminhash/)
Defined in: [packages/scalar-sketch/src/minhash.ts:115](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L115)
Create a byte-array-specialized MinHash signature.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`MinHashOptions`](/reference/knotkit/scalar-sketch/interfaces/minhashoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`BytesMinHash`](/reference/knotkit/scalar-sketch/interfaces/bytesminhash/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_SIGNATURE_SIZE` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# bytesSplitBlockBloomFilter
> **bytesSplitBlockBloomFilter**(`options`): [`BytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/bytessplitblockbloomfilter/)
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:180](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L180)
Create a byte-array-specialized Parquet-algorithm split-block Bloom filter.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`SplitBlockBloomFilterOptions`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`BytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/bytessplitblockbloomfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `INVALID_PROBABILITY`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# stringCountMinSketch
> **stringCountMinSketch**(`options?`): [`StringCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/stringcountminsketch/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:106](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L106)
Create a string-specialized Count-Min sketch.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`CountMinSketchOptions`](/reference/knotkit/scalar-sketch/interfaces/countminsketchoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`StringCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/stringcountminsketch/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_DIMENSION`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# stringHyperLogLog
> **stringHyperLogLog**(`options?`): [`StringHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/stringhyperloglog/)
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:149](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L149)
Create a string-specialized HyperLogLog.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`HyperLogLogOptions`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`StringHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/stringhyperloglog/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PRECISION` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# stringMinHash
> **stringMinHash**(`options?`): [`StringMinHash`](/reference/knotkit/scalar-sketch/interfaces/stringminhash/)
Defined in: [packages/scalar-sketch/src/minhash.ts:102](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L102)
Create a string-specialized MinHash signature.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`MinHashOptions`](/reference/knotkit/scalar-sketch/interfaces/minhashoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`StringMinHash`](/reference/knotkit/scalar-sketch/interfaces/stringminhash/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_SIGNATURE_SIZE` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# stringSplitBlockBloomFilter
> **stringSplitBlockBloomFilter**(`options`): [`StringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/stringsplitblockbloomfilter/)
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:167](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L167)
Create a string-specialized Parquet-algorithm split-block Bloom filter.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`SplitBlockBloomFilterOptions`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`StringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/stringsplitblockbloomfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `INVALID_PROBABILITY`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint32CountMinSketch
> **uint32CountMinSketch**(`options?`): [`Uint32CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint32countminsketch/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L130)
Create an unsigned-32-specialized Count-Min sketch.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`CountMinSketchOptions`](/reference/knotkit/scalar-sketch/interfaces/countminsketchoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint32CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint32countminsketch/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_DIMENSION`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint32HyperLogLog
> **uint32HyperLogLog**(`options?`): [`Uint32HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint32hyperloglog/)
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:175](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L175)
Create an unsigned-32-specialized HyperLogLog.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`HyperLogLogOptions`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint32HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint32hyperloglog/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PRECISION` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint32MinHash
> **uint32MinHash**(`options?`): [`Uint32MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint32minhash/)
Defined in: [packages/scalar-sketch/src/minhash.ts:128](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L128)
Create an unsigned-32-specialized MinHash signature.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`MinHashOptions`](/reference/knotkit/scalar-sketch/interfaces/minhashoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint32MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint32minhash/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_SIGNATURE_SIZE` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint32SplitBlockBloomFilter
> **uint32SplitBlockBloomFilter**(`options`): [`Uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint32splitblockbloomfilter/)
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:193](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L193)
Create an unsigned-32-specialized Parquet-algorithm split-block Bloom filter.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`SplitBlockBloomFilterOptions`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`Uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint32splitblockbloomfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `INVALID_PROBABILITY`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint64CountMinSketch
> **uint64CountMinSketch**(`options?`): [`Uint64CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint64countminsketch/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L142)
Create an unsigned-64-specialized Count-Min sketch.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`CountMinSketchOptions`](/reference/knotkit/scalar-sketch/interfaces/countminsketchoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint64CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint64countminsketch/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PROBABILITY`, `INVALID_DIMENSION`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint64HyperLogLog
> **uint64HyperLogLog**(`options?`): [`Uint64HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint64hyperloglog/)
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:188](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L188)
Create an unsigned-64-specialized HyperLogLog.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`HyperLogLogOptions`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint64HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint64hyperloglog/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_PRECISION` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint64MinHash
> **uint64MinHash**(`options?`): [`Uint64MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint64minhash/)
Defined in: [packages/scalar-sketch/src/minhash.ts:141](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L141)
Create an unsigned-64-specialized MinHash signature.
## Parameters
[Section titled “Parameters”](#parameters)
### options?
[Section titled “options?”](#options)
[`MinHashOptions`](/reference/knotkit/scalar-sketch/interfaces/minhashoptions/) = `{}`
## Returns
[Section titled “Returns”](#returns)
[`Uint64MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint64minhash/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_SIGNATURE_SIZE` or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# uint64SplitBlockBloomFilter
> **uint64SplitBlockBloomFilter**(`options`): [`Uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint64splitblockbloomfilter/)
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:206](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L206)
Create an unsigned-64-specialized Parquet-algorithm split-block Bloom filter.
## Parameters
[Section titled “Parameters”](#parameters)
### options
[Section titled “options”](#options)
[`SplitBlockBloomFilterOptions`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`Uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint64splitblockbloomfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_DIMENSION`, `INVALID_PROBABILITY`, or `STATE_TOO_LARGE` for invalid options.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for an invalid seed.
# BytesCountMinSketch
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:83](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L83)
A Count-Min sketch specialized for byte arrays.
## Extends
[Section titled “Extends”](#extends)
* [`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/)
* `CountMinSketchOperations`<`Uint8Array`, `BytesCountMinSketch`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L17)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#kind)
***
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L20)
Effective power-of-two column count.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`width`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#width)
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L22)
Effective prefix-stable row count, from 1 through 32.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`depth`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#depth)
***
### epsilon
[Section titled “epsilon”](#epsilon)
> `readonly` **epsilon**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L24)
Model-based additive error factor `e / width`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`epsilon`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#epsilon)
***
### confidence
[Section titled “confidence”](#confidence)
> `readonly` **confidence**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L26)
Model-based per-query confidence lower bound `1 - exp(-depth)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`confidence`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#confidence)
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L28)
Counter width, fixed at 32 bits.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`counterBits`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#counterbits)
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L30)
Accepted sum of update weights, capped at `2^32 - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`totalWeight`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#totalweight)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L32)
Bytes occupied by row-major counters, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#statebytelength)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L34)
XXH64 base seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L36)
Prefix-stable row-seed schedule that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seedschedule)
***
### update
[Section titled “update”](#update)
> **update**: (`value`, `weight?`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L48)
Add a non-negative unsigned 32-bit weight. Weight zero is a hash-free no-op.
All destination counters and the accepted total are checked before mutation.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`Uint8Array`
##### weight?
[Section titled “weight?”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_WEIGHT`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`CountMinSketchOperations.update`
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: (`value`) => `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L58)
Return the minimum counter selected across all rows. Does not mutate the sketch.
For accepted non-negative streams the result never underestimates the exact frequency. The `epsilon` and `confidence` metadata are the classical model bounds, assuming the domain-separated seeded XXH64 rows behave independently.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### See
[Section titled “See”](#see)
[An improved data stream summary: the Count-Min sketch](https://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf)
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`CountMinSketchOperations.estimate`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L66)
Add every counter and total from a compatible sketch into this sketch.
Self-merge uses the same additive semantics. Every overflow is rejected before mutation.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`BytesCountMinSketch`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`CountMinSketchOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetWidth`, `targetDepth`) => `BytesCountMinSketch`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L73)
Return a new sketch with congruent columns summed and a deterministic row prefix retained.
The target width must divide the current width and both dimensions may only decrease.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetWidth
[Section titled “targetWidth”](#targetwidth)
`number`
##### targetDepth
[Section titled “targetDepth”](#targetdepth)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`BytesCountMinSketch`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-13)
`CountMinSketchOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"bytes"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L85)
#### Overrides
[Section titled “Overrides”](#overrides)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#scalarkind)
# BytesHyperLogLog
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L68)
A HyperLogLog specialized for byte arrays.
## Extends
[Section titled “Extends”](#extends)
* [`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L13)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#kind)
***
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L16)
Effective register precision. The register count is `2 ** precision`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`precision`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#precision)
***
### registerCount
[Section titled “registerCount”](#registercount)
> `readonly` **registerCount**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L18)
Number of one-byte maximum-rank registers.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`registerCount`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#registercount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L20)
Bytes occupied by the mutable register state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#statebytelength)
***
### estimator
[Section titled “estimator”](#estimator)
> `readonly` **estimator**: `"ertl-improved-raw"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L22)
The cardinality estimator applied by [estimate](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimator`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimator)
***
### relativeStandardError
[Section titled “relativeStandardError”](#relativestandarderror)
> `readonly` **relativeStandardError**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L24)
Approximate one-standard-deviation relative error, `1.04 / sqrt(registerCount)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`relativeStandardError`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L26)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#seed)
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: () => `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L39)
Estimate the number of distinct updates. O(registerCount) after an update or merge that changes a register, O(1) for repeated or no-op reads; does not change the sketch’s registers.
Uses Otmar Ertl’s improved raw estimator without empirical lookup tables. The estimator is monotone, returns exactly zero for an empty sketch, and remains a floating-point query result rather than persisted state. The statistical error is described by [relativeStandardError](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror); it is not a hard bound.
#### Returns
[Section titled “Returns”](#returns)
`number`
#### See
[Section titled “See”](#see)
[New cardinality estimation algorithms for HyperLogLog sketches](https://oertl.github.io/hyperloglog-sketch-estimation-paper/paper/paper.pdf)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimate`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"bytes"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L69)
#### Overrides
[Section titled “Overrides”](#overrides)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L75)
Add one byte array to the distinct-count sketch. O(length); mutates the sketch.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid byte array.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L82)
Merge a compatible sketch by register maximum. O(registerCount); mutates only this sketch.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`BytesHyperLogLog`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetPrecision`) => `BytesHyperLogLog`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L89)
Return an exact reconstructed copy at a precision no larger than this one. O(registerCount). Top digest bits remain the index; discarded index bits become the target rank prefix.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### targetPrecision
[Section titled “targetPrecision”](#targetprecision)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`BytesHyperLogLog`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_REDUCTION` for an unsupported target.
# BytesMinHash
Defined in: [packages/scalar-sketch/src/minhash.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L81)
A MinHash signature specialized for byte arrays.
## Extends
[Section titled “Extends”](#extends)
* [`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/)
* `MinHashOperations`<`Uint8Array`, `BytesMinHash`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/minhash.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#kind)
***
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L18)
Number of ordered 64-bit coordinate minima.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`signatureSize`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#signaturesize)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L20)
Bytes occupied by paired low/high coordinate words, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#statebytelength)
***
### maximumStandardError
[Section titled “maximumStandardError”](#maximumstandarderror)
> `readonly` **maximumStandardError**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L22)
Worst-case standard error of the Jaccard estimate, `1 / (2 * sqrt(signatureSize))`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`maximumStandardError`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L24)
XXH64 base seed that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/minhash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L26)
Prefix-stable coordinate-seed schedule that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seedschedule)
***
### snapshot
[Section titled “snapshot”](#snapshot)
> `readonly` **snapshot**: () => `Uint32Array`
Defined in: [packages/scalar-sketch/src/minhash.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L37)
Return a fresh copy of the signature in O(signatureSize).
The array holds two Uint32 words per coordinate, low word first, in the same order as the serialized signature. Every word is `0xffff_ffff` when the sketch is empty. Mutating the copy leaves the sketch unchanged.
#### Returns
[Section titled “Returns”](#returns)
`Uint32Array`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`MinHashOperations.snapshot`
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L43)
Add one value to the set summary. Repeated values are idempotent. O(signatureSize).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`MinHashOperations.update`
***
### similarity
[Section titled “similarity”](#similarity)
> **similarity**: (`other`) => `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L57)
Estimate Jaccard similarity as the fraction of equal ordered coordinates. O(signatureSize).
Two empty signatures compare as `1`; exactly one empty signature compares as `0`. Otherwise, under the model assumption that domain-separated seeded XXH64 coordinates behave as independent min-wise hashes, the estimate has standard error `sqrt(J * (1 - J) / signatureSize)` and worst-case error metadata in [MinHashMetadata.maximumStandardError](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`BytesMinHash`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### See
[Section titled “See”](#see)
[Min-wise independent permutations](https://www.cs.princeton.edu/courses/archive/spring05/cos598E/bib/broder98minwise.pdf)
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH` for a non-comparable signature.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`MinHashOperations.similarity`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L65)
Summarize the set union by taking each compatible coordinate minimum. O(signatureSize).
Self-merge is idempotent and the source is never mutated.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other-1)
`BytesMinHash`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
#### Throws
[Section titled “Throws”](#throws-2)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`MinHashOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetSignatureSize`) => `BytesMinHash`
Defined in: [packages/scalar-sketch/src/minhash.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L72)
Return a new signature containing an ordered coordinate prefix. O(targetSignatureSize).
The target must be a supported power of two no larger than the current size.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetSignatureSize
[Section titled “targetSignatureSize”](#targetsignaturesize)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`BytesMinHash`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_REDUCTION` for an unsupported target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`MinHashOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"bytes"`
Defined in: [packages/scalar-sketch/src/minhash.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L82)
#### Overrides
[Section titled “Overrides”](#overrides)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#scalarkind)
# BytesSplitBlockBloomFilter
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L68)
A split-block Bloom filter specialized for byte arrays.
## Extends
[Section titled “Extends”](#extends)
* [`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#kind)
***
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L18)
Effective number of 256-bit blocks. Always a power of two.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`blockCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#blockcount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L20)
Bytes occupied by the mutable bit state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#statebytelength)
***
### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L22)
Number of accepted update attempts, including repeated values.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`updateCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#updatecount)
***
### estimatedFalsePositiveProbability
[Section titled “estimatedFalsePositiveProbability”](#estimatedfalsepositiveprobability)
> `readonly` **estimatedFalsePositiveProbability**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L31)
Current split-block Bloom model estimate.
The model averages each block’s eight-lane false-positive probability over its binomially distributed load. Counting attempts instead of distinct inputs makes the reported value conservative when callers repeat updates. The model assumes uniform XXH64 block selection and independent lanes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`estimatedFalsePositiveProbability`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#estimatedfalsepositiveprobability)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L33)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#seed)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"bytes"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L69)
#### Overrides
[Section titled “Overrides”](#overrides)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:76](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L76)
Add one byte array. O(length); mutates the filter.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid byte array.
#### Throws
[Section titled “Throws”](#throws-1)
With `CAPACITY_EXCEEDED` when the update count is full.
***
### mightContain
[Section titled “mightContain”](#mightcontain)
> **mightContain**: (`value`) => `boolean`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:82](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L82)
Return `false` for a definite miss and `true` for a possible member. O(length).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid byte array.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L89)
Union a compatible filter into this filter. O(blockCount); mutates only this filter.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`BytesSplitBlockBloomFilter`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, or `CAPACITY_EXCEEDED`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetBlockCount`) => `BytesSplitBlockBloomFilter`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L95)
Return a new filter folded to a power-of-two block count no larger than this one.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetBlockCount
[Section titled “targetBlockCount”](#targetblockcount)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`BytesSplitBlockBloomFilter`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
# CountMinCompatibilityConfig
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L30)
## Properties
[Section titled “Properties”](#properties)
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L31)
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L32)
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L33)
# CountMinSketchMetadata
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L16)
Read-only configuration and live frequency metadata shared by every scalar variant.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BytesCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/bytescountminsketch/)
* [`StringCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/stringcountminsketch/)
* [`Uint32CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint32countminsketch/)
* [`Uint64CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint64countminsketch/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L17)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L18)
***
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L20)
Effective power-of-two column count.
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L22)
Effective prefix-stable row count, from 1 through 32.
***
### epsilon
[Section titled “epsilon”](#epsilon)
> `readonly` **epsilon**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L24)
Model-based additive error factor `e / width`.
***
### confidence
[Section titled “confidence”](#confidence)
> `readonly` **confidence**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L26)
Model-based per-query confidence lower bound `1 - exp(-depth)`.
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L28)
Counter width, fixed at 32 bits.
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L30)
Accepted sum of update weights, capped at `2^32 - 1`.
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L32)
Bytes occupied by row-major counters, excluding object and hash-instance overhead.
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L34)
XXH64 base seed that participates in merge compatibility.
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L36)
Prefix-stable row-seed schedule that participates in merge compatibility.
# CountMinSketchOptions
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L6)
Construction options shared by the four scalar-specialized Count-Min factories.
## Properties
[Section titled “Properties”](#properties)
### epsilon?
[Section titled “epsilon?”](#epsilon)
> `readonly` `optional` **epsilon?**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L8)
Requested additive error factor. Defaults to `0.001`.
***
### confidence?
[Section titled “confidence?”](#confidence)
> `readonly` `optional` **confidence?**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L10)
Requested model confidence. Defaults to `0.99`.
***
### seed?
[Section titled “seed?”](#seed)
> `readonly` `optional` **seed?**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L12)
Unsigned base seed for the domain-separated SplitMix64 row schedule. Defaults to `0n`.
# HyperLogLogCompatibilityConfig
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L24)
## Properties
[Section titled “Properties”](#properties)
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:25](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L25)
***
### indexBits
[Section titled “indexBits”](#indexbits)
> `readonly` **indexBits**: `"high"`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L26)
***
### rankBits
[Section titled “rankBits”](#rankbits)
> `readonly` **rankBits**: `"remaining"`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L27)
# HyperLogLogMetadata
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L12)
Read-only configuration and accuracy metadata shared by every scalar variant.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BytesHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/byteshyperloglog/)
* [`StringHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/stringhyperloglog/)
* [`Uint32HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint32hyperloglog/)
* [`Uint64HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint64hyperloglog/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L13)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L14)
***
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L16)
Effective register precision. The register count is `2 ** precision`.
***
### registerCount
[Section titled “registerCount”](#registercount)
> `readonly` **registerCount**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L18)
Number of one-byte maximum-rank registers.
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L20)
Bytes occupied by the mutable register state, excluding object overhead.
***
### estimator
[Section titled “estimator”](#estimator)
> `readonly` **estimator**: `"ertl-improved-raw"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L22)
The cardinality estimator applied by [estimate](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate).
***
### relativeStandardError
[Section titled “relativeStandardError”](#relativestandarderror)
> `readonly` **relativeStandardError**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L24)
Approximate one-standard-deviation relative error, `1.04 / sqrt(registerCount)`.
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L26)
XXH64 seed that participates in merge compatibility.
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: () => `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L39)
Estimate the number of distinct updates. O(registerCount) after an update or merge that changes a register, O(1) for repeated or no-op reads; does not change the sketch’s registers.
Uses Otmar Ertl’s improved raw estimator without empirical lookup tables. The estimator is monotone, returns exactly zero for an empty sketch, and remains a floating-point query result rather than persisted state. The statistical error is described by [relativeStandardError](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror); it is not a hard bound.
#### Returns
[Section titled “Returns”](#returns)
`number`
#### See
[Section titled “See”](#see)
[New cardinality estimation algorithms for HyperLogLog sketches](https://oertl.github.io/hyperloglog-sketch-estimation-paper/paper/paper.pdf)
# HyperLogLogOptions
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L4)
Construction options shared by the four scalar-specialized HyperLogLog factories.
## Properties
[Section titled “Properties”](#properties)
### precision?
[Section titled “precision?”](#precision)
> `readonly` `optional` **precision?**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L6)
Register precision from 4 through 18. Defaults to 14.
***
### seed?
[Section titled “seed?”](#seed)
> `readonly` `optional` **seed?**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L8)
Unsigned XXH64 seed. Defaults to `0n`.
# MinHashCompatibilityConfig
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L36)
## Properties
[Section titled “Properties”](#properties)
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L37)
# MinHashMetadata
Defined in: [packages/scalar-sketch/src/minhash.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L14)
Read-only configuration and similarity-sampling metadata shared by every scalar variant.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BytesMinHash`](/reference/knotkit/scalar-sketch/interfaces/bytesminhash/)
* [`StringMinHash`](/reference/knotkit/scalar-sketch/interfaces/stringminhash/)
* [`Uint32MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint32minhash/)
* [`Uint64MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint64minhash/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/minhash.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L15)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/minhash.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L16)
***
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L18)
Number of ordered 64-bit coordinate minima.
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L20)
Bytes occupied by paired low/high coordinate words, excluding object and hash-instance overhead.
***
### maximumStandardError
[Section titled “maximumStandardError”](#maximumstandarderror)
> `readonly` **maximumStandardError**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L22)
Worst-case standard error of the Jaccard estimate, `1 / (2 * sqrt(signatureSize))`.
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L24)
XXH64 base seed that participates in comparison and merge compatibility.
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/minhash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L26)
Prefix-stable coordinate-seed schedule that participates in comparison and merge compatibility.
# MinHashOptions
Defined in: [packages/scalar-sketch/src/minhash.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L6)
Construction options shared by the four scalar-specialized MinHash factories.
## Properties
[Section titled “Properties”](#properties)
### signatureSize?
[Section titled “signatureSize?”](#signaturesize)
> `readonly` `optional` **signatureSize?**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L8)
Ordered coordinate count. Defaults to `128`; accepts powers of two from 16 through 4096.
***
### seed?
[Section titled “seed?”](#seed)
> `readonly` `optional` **seed?**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L10)
Unsigned base seed for the domain-separated SplitMix64 coordinate schedule. Defaults to `0n`.
# SketchCompatibilityConfigByKind
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L40)
## Properties
[Section titled “Properties”](#properties)
### split-block-bloom-filter
[Section titled “split-block-bloom-filter”](#split-block-bloom-filter)
> `readonly` **split-block-bloom-filter**: [`SplitBlockBloomCompatibilityConfig`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomcompatibilityconfig/)
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L41)
***
### hyperloglog
[Section titled “hyperloglog”](#hyperloglog)
> `readonly` **hyperloglog**: [`HyperLogLogCompatibilityConfig`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogcompatibilityconfig/)
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L42)
***
### count-min-sketch
[Section titled “count-min-sketch”](#count-min-sketch)
> `readonly` **count-min-sketch**: [`CountMinCompatibilityConfig`](/reference/knotkit/scalar-sketch/interfaces/countmincompatibilityconfig/)
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L43)
***
### minhash
[Section titled “minhash”](#minhash)
> `readonly` **minhash**: [`MinHashCompatibilityConfig`](/reference/knotkit/scalar-sketch/interfaces/minhashcompatibilityconfig/)
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L44)
# SplitBlockBloomCompatibilityConfig
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L20)
## Properties
[Section titled “Properties”](#properties)
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L21)
# SplitBlockBloomFilterMetadata
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L14)
Read-only configuration and live accuracy metadata shared by every scalar variant.
## Extended by
[Section titled “Extended by”](#extended-by)
* [`BytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/bytessplitblockbloomfilter/)
* [`StringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/stringsplitblockbloomfilter/)
* [`Uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint32splitblockbloomfilter/)
* [`Uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint64splitblockbloomfilter/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L15)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L16)
***
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L18)
Effective number of 256-bit blocks. Always a power of two.
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L20)
Bytes occupied by the mutable bit state, excluding object overhead.
***
### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L22)
Number of accepted update attempts, including repeated values.
***
### estimatedFalsePositiveProbability
[Section titled “estimatedFalsePositiveProbability”](#estimatedfalsepositiveprobability)
> `readonly` **estimatedFalsePositiveProbability**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L31)
Current split-block Bloom model estimate.
The model averages each block’s eight-lane false-positive probability over its binomially distributed load. Counting attempts instead of distinct inputs makes the reported value conservative when callers repeat updates. The model assumes uniform XXH64 block selection and independent lanes.
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L33)
XXH64 seed that participates in merge compatibility.
# SplitBlockBloomFilterOptions
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L4)
Construction options shared by the four scalar-specialized Bloom factories.
## Properties
[Section titled “Properties”](#properties)
### expectedEntries
[Section titled “expectedEntries”](#expectedentries)
> `readonly` **expectedEntries**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L6)
Expected number of updates used to size the initial filter.
***
### targetFalsePositiveProbability?
[Section titled “targetFalsePositiveProbability?”](#targetfalsepositiveprobability)
> `readonly` `optional` **targetFalsePositiveProbability?**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L8)
Model target at `expectedEntries`. Defaults to `0.01`.
***
### seed?
[Section titled “seed?”](#seed)
> `readonly` `optional` **seed?**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L10)
Unsigned XXH64 seed. Defaults to `0n`.
# StringCountMinSketch
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L77)
A Count-Min sketch specialized for strings.
## Extends
[Section titled “Extends”](#extends)
* [`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/)
* `CountMinSketchOperations`<`string`, `StringCountMinSketch`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L17)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#kind)
***
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L20)
Effective power-of-two column count.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`width`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#width)
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L22)
Effective prefix-stable row count, from 1 through 32.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`depth`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#depth)
***
### epsilon
[Section titled “epsilon”](#epsilon)
> `readonly` **epsilon**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L24)
Model-based additive error factor `e / width`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`epsilon`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#epsilon)
***
### confidence
[Section titled “confidence”](#confidence)
> `readonly` **confidence**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L26)
Model-based per-query confidence lower bound `1 - exp(-depth)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`confidence`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#confidence)
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L28)
Counter width, fixed at 32 bits.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`counterBits`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#counterbits)
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L30)
Accepted sum of update weights, capped at `2^32 - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`totalWeight`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#totalweight)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L32)
Bytes occupied by row-major counters, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#statebytelength)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L34)
XXH64 base seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L36)
Prefix-stable row-seed schedule that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seedschedule)
***
### update
[Section titled “update”](#update)
> **update**: (`value`, `weight?`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L48)
Add a non-negative unsigned 32-bit weight. Weight zero is a hash-free no-op.
All destination counters and the accepted total are checked before mutation.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`string`
##### weight?
[Section titled “weight?”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_WEIGHT`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`CountMinSketchOperations.update`
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: (`value`) => `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L58)
Return the minimum counter selected across all rows. Does not mutate the sketch.
For accepted non-negative streams the result never underestimates the exact frequency. The `epsilon` and `confidence` metadata are the classical model bounds, assuming the domain-separated seeded XXH64 rows behave independently.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### See
[Section titled “See”](#see)
[An improved data stream summary: the Count-Min sketch](https://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf)
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`CountMinSketchOperations.estimate`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L66)
Add every counter and total from a compatible sketch into this sketch.
Self-merge uses the same additive semantics. Every overflow is rejected before mutation.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`StringCountMinSketch`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`CountMinSketchOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetWidth`, `targetDepth`) => `StringCountMinSketch`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L73)
Return a new sketch with congruent columns summed and a deterministic row prefix retained.
The target width must divide the current width and both dimensions may only decrease.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetWidth
[Section titled “targetWidth”](#targetwidth)
`number`
##### targetDepth
[Section titled “targetDepth”](#targetdepth)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`StringCountMinSketch`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-13)
`CountMinSketchOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L79)
#### Overrides
[Section titled “Overrides”](#overrides)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#scalarkind)
# StringHyperLogLog
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L43)
A HyperLogLog specialized for strings.
## Extends
[Section titled “Extends”](#extends)
* [`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L13)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#kind)
***
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L16)
Effective register precision. The register count is `2 ** precision`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`precision`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#precision)
***
### registerCount
[Section titled “registerCount”](#registercount)
> `readonly` **registerCount**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L18)
Number of one-byte maximum-rank registers.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`registerCount`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#registercount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L20)
Bytes occupied by the mutable register state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#statebytelength)
***
### estimator
[Section titled “estimator”](#estimator)
> `readonly` **estimator**: `"ertl-improved-raw"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L22)
The cardinality estimator applied by [estimate](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimator`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimator)
***
### relativeStandardError
[Section titled “relativeStandardError”](#relativestandarderror)
> `readonly` **relativeStandardError**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L24)
Approximate one-standard-deviation relative error, `1.04 / sqrt(registerCount)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`relativeStandardError`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L26)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#seed)
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: () => `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L39)
Estimate the number of distinct updates. O(registerCount) after an update or merge that changes a register, O(1) for repeated or no-op reads; does not change the sketch’s registers.
Uses Otmar Ertl’s improved raw estimator without empirical lookup tables. The estimator is monotone, returns exactly zero for an empty sketch, and remains a floating-point query result rather than persisted state. The statistical error is described by [relativeStandardError](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror); it is not a hard bound.
#### Returns
[Section titled “Returns”](#returns)
`number`
#### See
[Section titled “See”](#see)
[New cardinality estimation algorithms for HyperLogLog sketches](https://oertl.github.io/hyperloglog-sketch-estimation-paper/paper/paper.pdf)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimate`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L44)
#### Overrides
[Section titled “Overrides”](#overrides)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L50)
Add one string to the distinct-count sketch. O(length); mutates the sketch.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid string.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L57)
Merge a compatible sketch by register maximum. O(registerCount); mutates only this sketch.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`StringHyperLogLog`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetPrecision`) => `StringHyperLogLog`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L64)
Return an exact reconstructed copy at a precision no larger than this one. O(registerCount). Top digest bits remain the index; discarded index bits become the target rank prefix.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### targetPrecision
[Section titled “targetPrecision”](#targetprecision)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`StringHyperLogLog`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_REDUCTION` for an unsupported target.
# StringMinHash
Defined in: [packages/scalar-sketch/src/minhash.ts:76](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L76)
A MinHash signature specialized for strings.
## Extends
[Section titled “Extends”](#extends)
* [`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/)
* `MinHashOperations`<`string`, `StringMinHash`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/minhash.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#kind)
***
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L18)
Number of ordered 64-bit coordinate minima.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`signatureSize`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#signaturesize)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L20)
Bytes occupied by paired low/high coordinate words, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#statebytelength)
***
### maximumStandardError
[Section titled “maximumStandardError”](#maximumstandarderror)
> `readonly` **maximumStandardError**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L22)
Worst-case standard error of the Jaccard estimate, `1 / (2 * sqrt(signatureSize))`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`maximumStandardError`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L24)
XXH64 base seed that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/minhash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L26)
Prefix-stable coordinate-seed schedule that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seedschedule)
***
### snapshot
[Section titled “snapshot”](#snapshot)
> `readonly` **snapshot**: () => `Uint32Array`
Defined in: [packages/scalar-sketch/src/minhash.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L37)
Return a fresh copy of the signature in O(signatureSize).
The array holds two Uint32 words per coordinate, low word first, in the same order as the serialized signature. Every word is `0xffff_ffff` when the sketch is empty. Mutating the copy leaves the sketch unchanged.
#### Returns
[Section titled “Returns”](#returns)
`Uint32Array`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`MinHashOperations.snapshot`
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L43)
Add one value to the set summary. Repeated values are idempotent. O(signatureSize).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`MinHashOperations.update`
***
### similarity
[Section titled “similarity”](#similarity)
> **similarity**: (`other`) => `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L57)
Estimate Jaccard similarity as the fraction of equal ordered coordinates. O(signatureSize).
Two empty signatures compare as `1`; exactly one empty signature compares as `0`. Otherwise, under the model assumption that domain-separated seeded XXH64 coordinates behave as independent min-wise hashes, the estimate has standard error `sqrt(J * (1 - J) / signatureSize)` and worst-case error metadata in [MinHashMetadata.maximumStandardError](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`StringMinHash`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### See
[Section titled “See”](#see)
[Min-wise independent permutations](https://www.cs.princeton.edu/courses/archive/spring05/cos598E/bib/broder98minwise.pdf)
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH` for a non-comparable signature.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`MinHashOperations.similarity`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L65)
Summarize the set union by taking each compatible coordinate minimum. O(signatureSize).
Self-merge is idempotent and the source is never mutated.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other-1)
`StringMinHash`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
#### Throws
[Section titled “Throws”](#throws-2)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`MinHashOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetSignatureSize`) => `StringMinHash`
Defined in: [packages/scalar-sketch/src/minhash.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L72)
Return a new signature containing an ordered coordinate prefix. O(targetSignatureSize).
The target must be a supported power of two no larger than the current size.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetSignatureSize
[Section titled “targetSignatureSize”](#targetsignaturesize)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`StringMinHash`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_REDUCTION` for an unsupported target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`MinHashOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"`
Defined in: [packages/scalar-sketch/src/minhash.ts:77](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L77)
#### Overrides
[Section titled “Overrides”](#overrides)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#scalarkind)
# StringSplitBlockBloomFilter
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L37)
A split-block Bloom filter specialized for strings.
## Extends
[Section titled “Extends”](#extends)
* [`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#kind)
***
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L18)
Effective number of 256-bit blocks. Always a power of two.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`blockCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#blockcount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L20)
Bytes occupied by the mutable bit state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#statebytelength)
***
### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L22)
Number of accepted update attempts, including repeated values.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`updateCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#updatecount)
***
### estimatedFalsePositiveProbability
[Section titled “estimatedFalsePositiveProbability”](#estimatedfalsepositiveprobability)
> `readonly` **estimatedFalsePositiveProbability**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L31)
Current split-block Bloom model estimate.
The model averages each block’s eight-lane false-positive probability over its binomially distributed load. Counting attempts instead of distinct inputs makes the reported value conservative when callers repeat updates. The model assumes uniform XXH64 block selection and independent lanes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`estimatedFalsePositiveProbability`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#estimatedfalsepositiveprobability)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L33)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#seed)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L38)
#### Overrides
[Section titled “Overrides”](#overrides)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L45)
Add one string. O(length); mutates the filter.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`string`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid string.
#### Throws
[Section titled “Throws”](#throws-1)
With `CAPACITY_EXCEEDED` when the update count is full.
***
### mightContain
[Section titled “mightContain”](#mightcontain)
> **mightContain**: (`value`) => `boolean`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L51)
Return `false` for a definite miss and `true` for a possible member. O(length).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid string.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L58)
Union a compatible filter into this filter. O(blockCount); mutates only this filter.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`StringSplitBlockBloomFilter`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, or `CAPACITY_EXCEEDED`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetBlockCount`) => `StringSplitBlockBloomFilter`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L64)
Return a new filter folded to a power-of-two block count no larger than this one.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetBlockCount
[Section titled “targetBlockCount”](#targetblockcount)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`StringSplitBlockBloomFilter`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
# Uint32CountMinSketch
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:89](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L89)
A Count-Min sketch specialized for unsigned 32-bit numbers.
## Extends
[Section titled “Extends”](#extends)
* [`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/)
* `CountMinSketchOperations`<`number`, `Uint32CountMinSketch`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L17)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#kind)
***
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L20)
Effective power-of-two column count.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`width`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#width)
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L22)
Effective prefix-stable row count, from 1 through 32.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`depth`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#depth)
***
### epsilon
[Section titled “epsilon”](#epsilon)
> `readonly` **epsilon**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L24)
Model-based additive error factor `e / width`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`epsilon`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#epsilon)
***
### confidence
[Section titled “confidence”](#confidence)
> `readonly` **confidence**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L26)
Model-based per-query confidence lower bound `1 - exp(-depth)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`confidence`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#confidence)
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L28)
Counter width, fixed at 32 bits.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`counterBits`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#counterbits)
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L30)
Accepted sum of update weights, capped at `2^32 - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`totalWeight`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#totalweight)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L32)
Bytes occupied by row-major counters, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#statebytelength)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L34)
XXH64 base seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L36)
Prefix-stable row-seed schedule that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seedschedule)
***
### update
[Section titled “update”](#update)
> **update**: (`value`, `weight?`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L48)
Add a non-negative unsigned 32-bit weight. Weight zero is a hash-free no-op.
All destination counters and the accepted total are checked before mutation.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
##### weight?
[Section titled “weight?”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_WEIGHT`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`CountMinSketchOperations.update`
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: (`value`) => `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L58)
Return the minimum counter selected across all rows. Does not mutate the sketch.
For accepted non-negative streams the result never underestimates the exact frequency. The `epsilon` and `confidence` metadata are the classical model bounds, assuming the domain-separated seeded XXH64 rows behave independently.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### See
[Section titled “See”](#see)
[An improved data stream summary: the Count-Min sketch](https://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf)
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`CountMinSketchOperations.estimate`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L66)
Add every counter and total from a compatible sketch into this sketch.
Self-merge uses the same additive semantics. Every overflow is rejected before mutation.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`Uint32CountMinSketch`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`CountMinSketchOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetWidth`, `targetDepth`) => `Uint32CountMinSketch`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L73)
Return a new sketch with congruent columns summed and a deterministic row prefix retained.
The target width must divide the current width and both dimensions may only decrease.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetWidth
[Section titled “targetWidth”](#targetwidth)
`number`
##### targetDepth
[Section titled “targetDepth”](#targetdepth)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint32CountMinSketch`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-13)
`CountMinSketchOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint32"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L91)
#### Overrides
[Section titled “Overrides”](#overrides)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#scalarkind)
# Uint32HyperLogLog
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L93)
A HyperLogLog specialized for unsigned 32-bit numbers.
## Extends
[Section titled “Extends”](#extends)
* [`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L13)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#kind)
***
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L16)
Effective register precision. The register count is `2 ** precision`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`precision`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#precision)
***
### registerCount
[Section titled “registerCount”](#registercount)
> `readonly` **registerCount**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L18)
Number of one-byte maximum-rank registers.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`registerCount`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#registercount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L20)
Bytes occupied by the mutable register state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#statebytelength)
***
### estimator
[Section titled “estimator”](#estimator)
> `readonly` **estimator**: `"ertl-improved-raw"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L22)
The cardinality estimator applied by [estimate](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimator`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimator)
***
### relativeStandardError
[Section titled “relativeStandardError”](#relativestandarderror)
> `readonly` **relativeStandardError**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L24)
Approximate one-standard-deviation relative error, `1.04 / sqrt(registerCount)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`relativeStandardError`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L26)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#seed)
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: () => `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L39)
Estimate the number of distinct updates. O(registerCount) after an update or merge that changes a register, O(1) for repeated or no-op reads; does not change the sketch’s registers.
Uses Otmar Ertl’s improved raw estimator without empirical lookup tables. The estimator is monotone, returns exactly zero for an empty sketch, and remains a floating-point query result rather than persisted state. The statistical error is described by [relativeStandardError](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror); it is not a hard bound.
#### Returns
[Section titled “Returns”](#returns)
`number`
#### See
[Section titled “See”](#see)
[New cardinality estimation algorithms for HyperLogLog sketches](https://oertl.github.io/hyperloglog-sketch-estimation-paper/paper/paper.pdf)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimate`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint32"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:94](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L94)
#### Overrides
[Section titled “Overrides”](#overrides)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:100](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L100)
Add one unsigned 32-bit number to the distinct-count sketch. O(1); mutates the sketch.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` when the value is outside the unsigned 32-bit domain.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L107)
Merge a compatible sketch by register maximum. O(registerCount); mutates only this sketch.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`Uint32HyperLogLog`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetPrecision`) => `Uint32HyperLogLog`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:114](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L114)
Return an exact reconstructed copy at a precision no larger than this one. O(registerCount). Top digest bits remain the index; discarded index bits become the target rank prefix.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### targetPrecision
[Section titled “targetPrecision”](#targetprecision)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint32HyperLogLog`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_REDUCTION` for an unsupported target.
# Uint32MinHash
Defined in: [packages/scalar-sketch/src/minhash.ts:86](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L86)
A MinHash signature specialized for unsigned 32-bit numbers.
## Extends
[Section titled “Extends”](#extends)
* [`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/)
* `MinHashOperations`<`number`, `Uint32MinHash`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/minhash.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#kind)
***
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L18)
Number of ordered 64-bit coordinate minima.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`signatureSize`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#signaturesize)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L20)
Bytes occupied by paired low/high coordinate words, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#statebytelength)
***
### maximumStandardError
[Section titled “maximumStandardError”](#maximumstandarderror)
> `readonly` **maximumStandardError**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L22)
Worst-case standard error of the Jaccard estimate, `1 / (2 * sqrt(signatureSize))`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`maximumStandardError`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L24)
XXH64 base seed that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/minhash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L26)
Prefix-stable coordinate-seed schedule that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seedschedule)
***
### snapshot
[Section titled “snapshot”](#snapshot)
> `readonly` **snapshot**: () => `Uint32Array`
Defined in: [packages/scalar-sketch/src/minhash.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L37)
Return a fresh copy of the signature in O(signatureSize).
The array holds two Uint32 words per coordinate, low word first, in the same order as the serialized signature. Every word is `0xffff_ffff` when the sketch is empty. Mutating the copy leaves the sketch unchanged.
#### Returns
[Section titled “Returns”](#returns)
`Uint32Array`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`MinHashOperations.snapshot`
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L43)
Add one value to the set summary. Repeated values are idempotent. O(signatureSize).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`MinHashOperations.update`
***
### similarity
[Section titled “similarity”](#similarity)
> **similarity**: (`other`) => `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L57)
Estimate Jaccard similarity as the fraction of equal ordered coordinates. O(signatureSize).
Two empty signatures compare as `1`; exactly one empty signature compares as `0`. Otherwise, under the model assumption that domain-separated seeded XXH64 coordinates behave as independent min-wise hashes, the estimate has standard error `sqrt(J * (1 - J) / signatureSize)` and worst-case error metadata in [MinHashMetadata.maximumStandardError](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`Uint32MinHash`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### See
[Section titled “See”](#see)
[Min-wise independent permutations](https://www.cs.princeton.edu/courses/archive/spring05/cos598E/bib/broder98minwise.pdf)
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH` for a non-comparable signature.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`MinHashOperations.similarity`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L65)
Summarize the set union by taking each compatible coordinate minimum. O(signatureSize).
Self-merge is idempotent and the source is never mutated.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other-1)
`Uint32MinHash`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
#### Throws
[Section titled “Throws”](#throws-2)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`MinHashOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetSignatureSize`) => `Uint32MinHash`
Defined in: [packages/scalar-sketch/src/minhash.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L72)
Return a new signature containing an ordered coordinate prefix. O(targetSignatureSize).
The target must be a supported power of two no larger than the current size.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetSignatureSize
[Section titled “targetSignatureSize”](#targetsignaturesize)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`Uint32MinHash`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_REDUCTION` for an unsupported target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`MinHashOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint32"`
Defined in: [packages/scalar-sketch/src/minhash.ts:87](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L87)
#### Overrides
[Section titled “Overrides”](#overrides)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#scalarkind)
# Uint32SplitBlockBloomFilter
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:99](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L99)
A split-block Bloom filter specialized for unsigned 32-bit numbers.
## Extends
[Section titled “Extends”](#extends)
* [`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#kind)
***
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L18)
Effective number of 256-bit blocks. Always a power of two.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`blockCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#blockcount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L20)
Bytes occupied by the mutable bit state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#statebytelength)
***
### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L22)
Number of accepted update attempts, including repeated values.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`updateCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#updatecount)
***
### estimatedFalsePositiveProbability
[Section titled “estimatedFalsePositiveProbability”](#estimatedfalsepositiveprobability)
> `readonly` **estimatedFalsePositiveProbability**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L31)
Current split-block Bloom model estimate.
The model averages each block’s eight-lane false-positive probability over its binomially distributed load. Counting attempts instead of distinct inputs makes the reported value conservative when callers repeat updates. The model assumes uniform XXH64 block selection and independent lanes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`estimatedFalsePositiveProbability`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#estimatedfalsepositiveprobability)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L33)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#seed)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint32"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:100](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L100)
#### Overrides
[Section titled “Overrides”](#overrides)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:107](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L107)
Add one unsigned 32-bit number. O(1); mutates the filter.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` when the value is outside the unsigned 32-bit domain.
#### Throws
[Section titled “Throws”](#throws-1)
With `CAPACITY_EXCEEDED` when the update count is full.
***
### mightContain
[Section titled “mightContain”](#mightcontain)
> **mightContain**: (`value`) => `boolean`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:113](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L113)
Return `false` for a definite miss and `true` for a possible member. O(1).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` when the value is outside the unsigned 32-bit domain.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:120](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L120)
Union a compatible filter into this filter. O(blockCount); mutates only this filter.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`Uint32SplitBlockBloomFilter`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, or `CAPACITY_EXCEEDED`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetBlockCount`) => `Uint32SplitBlockBloomFilter`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:126](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L126)
Return a new filter folded to a power-of-two block count no larger than this one.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetBlockCount
[Section titled “targetBlockCount”](#targetblockcount)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint32SplitBlockBloomFilter`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
# Uint64CountMinSketch
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L95)
A Count-Min sketch specialized for exact unsigned 64-bit bigints.
## Extends
[Section titled “Extends”](#extends)
* [`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/)
* `CountMinSketchOperations`<`bigint`, `Uint64CountMinSketch`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L17)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#kind)
***
### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L20)
Effective power-of-two column count.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`width`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#width)
***
### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L22)
Effective prefix-stable row count, from 1 through 32.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`depth`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#depth)
***
### epsilon
[Section titled “epsilon”](#epsilon)
> `readonly` **epsilon**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L24)
Model-based additive error factor `e / width`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`epsilon`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#epsilon)
***
### confidence
[Section titled “confidence”](#confidence)
> `readonly` **confidence**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L26)
Model-based per-query confidence lower bound `1 - exp(-depth)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`confidence`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#confidence)
***
### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L28)
Counter width, fixed at 32 bits.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`counterBits`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#counterbits)
***
### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L30)
Accepted sum of update weights, capped at `2^32 - 1`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`totalWeight`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#totalweight)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L32)
Bytes occupied by row-major counters, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#statebytelength)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L34)
XXH64 base seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L36)
Prefix-stable row-seed schedule that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#seedschedule)
***
### update
[Section titled “update”](#update)
> **update**: (`value`, `weight?`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L48)
Add a non-negative unsigned 32-bit weight. Weight zero is a hash-free no-op.
All destination counters and the accepted total are checked before mutation.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`bigint`
##### weight?
[Section titled “weight?”](#weight)
`number`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_WEIGHT`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`CountMinSketchOperations.update`
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: (`value`) => `number`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L58)
Return the minimum counter selected across all rows. Does not mutate the sketch.
For accepted non-negative streams the result never underestimates the exact frequency. The `epsilon` and `confidence` metadata are the classical model bounds, assuming the domain-separated seeded XXH64 rows behave independently.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`bigint`
#### Returns
[Section titled “Returns”](#returns-1)
`number`
#### See
[Section titled “See”](#see)
[An improved data stream summary: the Count-Min sketch](https://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf)
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-11)
`CountMinSketchOperations.estimate`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:66](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L66)
Add every counter and total from a compatible sketch into this sketch.
Self-merge uses the same additive semantics. Every overflow is rejected before mutation.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`Uint64CountMinSketch`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, `CAPACITY_EXCEEDED`, or `COUNTER_OVERFLOW`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-12)
`CountMinSketchOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetWidth`, `targetDepth`) => `Uint64CountMinSketch`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L73)
Return a new sketch with congruent columns summed and a deterministic row prefix retained.
The target width must divide the current width and both dimensions may only decrease.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetWidth
[Section titled “targetWidth”](#targetwidth)
`number`
##### targetDepth
[Section titled “targetDepth”](#targetdepth)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint64CountMinSketch`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-13)
`CountMinSketchOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint64"`
Defined in: [packages/scalar-sketch/src/count-min-sketch.ts:97](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/count-min-sketch.ts#L97)
#### Overrides
[Section titled “Overrides”](#overrides)
[`CountMinSketchMetadata`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/countminsketchmetadata/#scalarkind)
# Uint64HyperLogLog
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:118](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L118)
A HyperLogLog specialized for exact unsigned 64-bit bigints.
## Extends
[Section titled “Extends”](#extends)
* [`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L13)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#kind)
***
### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L16)
Effective register precision. The register count is `2 ** precision`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`precision`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#precision)
***
### registerCount
[Section titled “registerCount”](#registercount)
> `readonly` **registerCount**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L18)
Number of one-byte maximum-rank registers.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`registerCount`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#registercount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L20)
Bytes occupied by the mutable register state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#statebytelength)
***
### estimator
[Section titled “estimator”](#estimator)
> `readonly` **estimator**: `"ertl-improved-raw"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L22)
The cardinality estimator applied by [estimate](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate).
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimator`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimator)
***
### relativeStandardError
[Section titled “relativeStandardError”](#relativestandarderror)
> `readonly` **relativeStandardError**: `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L24)
Approximate one-standard-deviation relative error, `1.04 / sqrt(registerCount)`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`relativeStandardError`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L26)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#seed)
***
### estimate
[Section titled “estimate”](#estimate)
> **estimate**: () => `number`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L39)
Estimate the number of distinct updates. O(registerCount) after an update or merge that changes a register, O(1) for repeated or no-op reads; does not change the sketch’s registers.
Uses Otmar Ertl’s improved raw estimator without empirical lookup tables. The estimator is monotone, returns exactly zero for an empty sketch, and remains a floating-point query result rather than persisted state. The statistical error is described by [relativeStandardError](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#relativestandarderror); it is not a hard bound.
#### Returns
[Section titled “Returns”](#returns)
`number`
#### See
[Section titled “See”](#see)
[New cardinality estimation algorithms for HyperLogLog sketches](https://oertl.github.io/hyperloglog-sketch-estimation-paper/paper/paper.pdf)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`estimate`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#estimate)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint64"`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:119](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L119)
#### Overrides
[Section titled “Overrides”](#overrides)
[`HyperLogLogMetadata`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/hyperloglogmetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:125](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L125)
Add one unsigned 64-bit bigint to the distinct-count sketch. O(1); mutates the sketch.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`bigint`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` when the value is outside the unsigned 64-bit domain.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:132](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L132)
Merge a compatible sketch by register maximum. O(registerCount); mutates only this sketch.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`Uint64HyperLogLog`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetPrecision`) => `Uint64HyperLogLog`
Defined in: [packages/scalar-sketch/src/hyperloglog.ts:139](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/hyperloglog.ts#L139)
Return an exact reconstructed copy at a precision no larger than this one. O(registerCount). Top digest bits remain the index; discarded index bits become the target rank prefix.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### targetPrecision
[Section titled “targetPrecision”](#targetprecision)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint64HyperLogLog`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_REDUCTION` for an unsupported target.
# Uint64MinHash
Defined in: [packages/scalar-sketch/src/minhash.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L91)
A MinHash signature specialized for exact unsigned 64-bit bigints.
## Extends
[Section titled “Extends”](#extends)
* [`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/)
* `MinHashOperations`<`bigint`, `Uint64MinHash`>
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/minhash.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#kind)
***
### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L18)
Number of ordered 64-bit coordinate minima.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`signatureSize`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#signaturesize)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L20)
Bytes occupied by paired low/high coordinate words, excluding object and hash-instance overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#statebytelength)
***
### maximumStandardError
[Section titled “maximumStandardError”](#maximumstandarderror)
> `readonly` **maximumStandardError**: `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L22)
Worst-case standard error of the Jaccard estimate, `1 / (2 * sqrt(signatureSize))`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`maximumStandardError`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/minhash.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L24)
XXH64 base seed that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seed)
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/minhash.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L26)
Prefix-stable coordinate-seed schedule that participates in comparison and merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`seedSchedule`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#seedschedule)
***
### snapshot
[Section titled “snapshot”](#snapshot)
> `readonly` **snapshot**: () => `Uint32Array`
Defined in: [packages/scalar-sketch/src/minhash.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L37)
Return a fresh copy of the signature in O(signatureSize).
The array holds two Uint32 words per coordinate, low word first, in the same order as the serialized signature. Every word is `0xffff_ffff` when the sketch is empty. Mutating the copy leaves the sketch unchanged.
#### Returns
[Section titled “Returns”](#returns)
`Uint32Array`
#### Inherited from
[Section titled “Inherited from”](#inherited-from-6)
`MinHashOperations.snapshot`
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L43)
Add one value to the set summary. Repeated values are idempotent. O(signatureSize).
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`bigint`
#### Returns
[Section titled “Returns”](#returns-1)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` for an invalid scalar value.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-7)
`MinHashOperations.update`
***
### similarity
[Section titled “similarity”](#similarity)
> **similarity**: (`other`) => `number`
Defined in: [packages/scalar-sketch/src/minhash.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L57)
Estimate Jaccard similarity as the fraction of equal ordered coordinates. O(signatureSize).
Two empty signatures compare as `1`; exactly one empty signature compares as `0`. Otherwise, under the model assumption that domain-separated seeded XXH64 coordinates behave as independent min-wise hashes, the estimate has standard error `sqrt(J * (1 - J) / signatureSize)` and worst-case error metadata in [MinHashMetadata.maximumStandardError](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#maximumstandarderror).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### other
[Section titled “other”](#other)
`Uint64MinHash`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
#### See
[Section titled “See”](#see)
[Min-wise independent permutations](https://www.cs.princeton.edu/courses/archive/spring05/cos598E/bib/broder98minwise.pdf)
#### Throws
[Section titled “Throws”](#throws-1)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH` for a non-comparable signature.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-8)
`MinHashOperations.similarity`
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/minhash.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L65)
Summarize the set union by taking each compatible coordinate minimum. O(signatureSize).
Self-merge is idempotent and the source is never mutated.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other-1)
`Uint64MinHash`
#### Returns
[Section titled “Returns”](#returns-3)
`void`
#### Throws
[Section titled “Throws”](#throws-2)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `INCOMPATIBLE_SKETCH`.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-9)
`MinHashOperations.merge`
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetSignatureSize`) => `Uint64MinHash`
Defined in: [packages/scalar-sketch/src/minhash.ts:72](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L72)
Return a new signature containing an ordered coordinate prefix. O(targetSignatureSize).
The target must be a supported power of two no larger than the current size.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetSignatureSize
[Section titled “targetSignatureSize”](#targetsignaturesize)
`number`
#### Returns
[Section titled “Returns”](#returns-4)
`Uint64MinHash`
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_REDUCTION` for an unsupported target.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-10)
`MinHashOperations.reduce`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint64"`
Defined in: [packages/scalar-sketch/src/minhash.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/minhash.ts#L92)
#### Overrides
[Section titled “Overrides”](#overrides)
[`MinHashMetadata`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/minhashmetadata/#scalarkind)
# Uint64SplitBlockBloomFilter
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:130](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L130)
A split-block Bloom filter specialized for exact unsigned 64-bit bigints.
## Extends
[Section titled “Extends”](#extends)
* [`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L15)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`kind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#kind)
***
### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L18)
Effective number of 256-bit blocks. Always a power of two.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`blockCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#blockcount)
***
### stateByteLength
[Section titled “stateByteLength”](#statebytelength)
> `readonly` **stateByteLength**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L20)
Bytes occupied by the mutable bit state, excluding object overhead.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`stateByteLength`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#statebytelength)
***
### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L22)
Number of accepted update attempts, including repeated values.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`updateCount`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#updatecount)
***
### estimatedFalsePositiveProbability
[Section titled “estimatedFalsePositiveProbability”](#estimatedfalsepositiveprobability)
> `readonly` **estimatedFalsePositiveProbability**: `number`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L31)
Current split-block Bloom model estimate.
The model averages each block’s eight-lane false-positive probability over its binomially distributed load. Counting attempts instead of distinct inputs makes the reported value conservative when callers repeat updates. The model assumes uniform XXH64 block selection and independent lanes.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`estimatedFalsePositiveProbability`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#estimatedfalsepositiveprobability)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `bigint`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L33)
XXH64 seed that participates in merge compatibility.
#### Inherited from
[Section titled “Inherited from”](#inherited-from-5)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`seed`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#seed)
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"uint64"`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:131](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L131)
#### Overrides
[Section titled “Overrides”](#overrides)
[`SplitBlockBloomFilterMetadata`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/).[`scalarKind`](/reference/knotkit/scalar-sketch/interfaces/splitblockbloomfiltermetadata/#scalarkind)
***
### update
[Section titled “update”](#update)
> **update**: (`value`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:138](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L138)
Add one unsigned 64-bit bigint. O(1); mutates the filter.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`bigint`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
From `knotkit/hash` when the value is outside the unsigned 64-bit domain.
#### Throws
[Section titled “Throws”](#throws-1)
With `CAPACITY_EXCEEDED` when the update count is full.
***
### mightContain
[Section titled “mightContain”](#mightcontain)
> **mightContain**: (`value`) => `boolean`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:144](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L144)
Return `false` for a definite miss and `true` for a possible member. O(1).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`bigint`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-2)
From `knotkit/hash` when the value is outside the unsigned 64-bit domain.
***
### merge
[Section titled “merge”](#merge)
> **merge**: (`other`) => `void`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:151](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L151)
Union a compatible filter into this filter. O(blockCount); mutates only this filter.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### other
[Section titled “other”](#other)
`Uint64SplitBlockBloomFilter`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws-3)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, `INCOMPATIBLE_SKETCH`, or `CAPACITY_EXCEEDED`.
***
### reduce
[Section titled “reduce”](#reduce)
> **reduce**: (`targetBlockCount`) => `Uint64SplitBlockBloomFilter`
Defined in: [packages/scalar-sketch/src/split-block-bloom-filter.ts:157](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/split-block-bloom-filter.ts#L157)
Return a new filter folded to a power-of-two block count no larger than this one.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### targetBlockCount
[Section titled “targetBlockCount”](#targetblockcount)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Uint64SplitBlockBloomFilter`
#### Throws
[Section titled “Throws”](#throws-4)
With `INVALID_REDUCTION` for an unsound target.
# ScalarKind
> **ScalarKind** = *typeof* [`SCALAR_KINDS`](/reference/knotkit/scalar-sketch/variables/scalar_kinds/)\[`number`]
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L10)
# ScalarSketch
> **ScalarSketch** = [`StringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/stringsplitblockbloomfilter/) | [`BytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/bytessplitblockbloomfilter/) | [`Uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint32splitblockbloomfilter/) | [`Uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/interfaces/uint64splitblockbloomfilter/) | [`StringHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/stringhyperloglog/) | [`BytesHyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/byteshyperloglog/) | [`Uint32HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint32hyperloglog/) | [`Uint64HyperLogLog`](/reference/knotkit/scalar-sketch/interfaces/uint64hyperloglog/) | [`StringCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/stringcountminsketch/) | [`BytesCountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/bytescountminsketch/) | [`Uint32CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint32countminsketch/) | [`Uint64CountMinSketch`](/reference/knotkit/scalar-sketch/interfaces/uint64countminsketch/) | [`StringMinHash`](/reference/knotkit/scalar-sketch/interfaces/stringminhash/) | [`BytesMinHash`](/reference/knotkit/scalar-sketch/interfaces/bytesminhash/) | [`Uint32MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint32minhash/) | [`Uint64MinHash`](/reference/knotkit/scalar-sketch/interfaces/uint64minhash/)
Defined in: [packages/scalar-sketch/src/scalar-sketch.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/scalar-sketch.ts#L16)
# ScalarSketchErrorCode
> **ScalarSketchErrorCode** = [`ScalarSketchInvalidInputErrorCode`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchinvalidinputerrorcode/) | [`ScalarSketchParseErrorCode`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketchparseerrorcode/)
Defined in: [packages/scalar-sketch/src/errors.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L47)
# ScalarSketchInvalidInputErrorCode
> **ScalarSketchInvalidInputErrorCode** = *typeof* [`SCALAR_SKETCH_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/scalar-sketch/variables/scalar_sketch_invalid_input_error_codes/)\[`number`]
Defined in: [packages/scalar-sketch/src/errors.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L45)
# ScalarSketchParseErrorCode
> **ScalarSketchParseErrorCode** = *typeof* [`SCALAR_SKETCH_PARSE_ERROR_CODES`](/reference/knotkit/scalar-sketch/variables/scalar_sketch_parse_error_codes/)\[`number`]
Defined in: [packages/scalar-sketch/src/errors.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L46)
# SeedScheduleIdentity
> **SeedScheduleIdentity** = { `kind`: `"single"`; `version`: `1`; } | { `kind`: `"splitmix64"`; `version`: `1`; }
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L12)
# SketchCompatibilityIdentity
> **SketchCompatibilityIdentity**<`Kind`> = `{ readonly [Family in Kind]: { kind: Family; scalarKind: ScalarKind; hash: AnyHashIdentity; seedSchedule: SeedScheduleIdentity; config: SketchCompatibilityConfigByKind[Family] } }`\[`Kind`]
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L47)
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* [`SketchKind`](/reference/knotkit/scalar-sketch/type-aliases/sketchkind/) = [`SketchKind`](/reference/knotkit/scalar-sketch/type-aliases/sketchkind/)
# SketchKind
> **SketchKind** = *typeof* [`SKETCH_KINDS`](/reference/knotkit/scalar-sketch/variables/sketch_kinds/)\[`number`]
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L6)
# SCALAR_KINDS
> `const` **SCALAR_KINDS**: readonly \[`"string"`, `"bytes"`, `"uint32"`, `"uint64"`]
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L8)
# SCALAR_SKETCH_ERROR_CODES
> `const` **SCALAR_SKETCH_ERROR_CODES**: readonly [`ScalarSketchErrorCode`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketcherrorcode/)\[]
Defined in: [packages/scalar-sketch/src/errors.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L50)
Every code emitted by `knotkit/scalar-sketch`, in stable category order.
# SCALAR_SKETCH_INVALID_INPUT_ERROR_CODES
> `const` **SCALAR_SKETCH_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_PROBABILITY"`, `"INVALID_DIMENSION"`, `"INVALID_PRECISION"`, `"INVALID_SIGNATURE_SIZE"`, `"STATE_TOO_LARGE"`, `"FOREIGN_STRUCTURE"`, `"WRONG_FAMILY"`, `"INCOMPATIBLE_SKETCH"`, `"INVALID_REDUCTION"`, `"INVALID_WEIGHT"`, `"CAPACITY_EXCEEDED"`, `"COUNTER_OVERFLOW"`]
Defined in: [packages/scalar-sketch/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L4)
Every live-structure error code emitted by [ScalarSketchInvalidInputError](/reference/knotkit/scalar-sketch/classes/scalarsketchinvalidinputerror/).
# SCALAR_SKETCH_PARSE_ERROR_CODES
> `const` **SCALAR_SKETCH_PARSE_ERROR_CODES**: readonly \[`"INVALID_SHAPE"`, `"INVALID_ENVELOPE"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`, `"INVALID_PACKAGE_HEADER"`, `"UNKNOWN_KIND"`, `"UNKNOWN_SCALAR_KIND"`, `"UNSUPPORTED_WIRE_VERSION"`, `"UNSUPPORTED_PRODUCER_VERSION"`, `"UNSUPPORTED_SCHEDULE"`, `"INVALID_STATE"`, `"STATE_TOO_LARGE"`]
Defined in: [packages/scalar-sketch/src/errors.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/errors.ts#L20)
Every persistence-envelope error code emitted by [ScalarSketchParseError](/reference/knotkit/scalar-sketch/classes/scalarsketchparseerror/).
# SCALAR_SKETCH_WIRE_VERSION
> `const` **SCALAR_SKETCH_WIRE_VERSION**: `1` = `1`
Defined in: [packages/scalar-sketch/src/version.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/version.ts#L5)
The scalar-sketch serialization format version. It is the payload version of the binary envelope and the `wireVersion` field of the JSON projection; both decoders reject any other value.
# SKETCH_KINDS
> `const` **SKETCH_KINDS**: readonly \[`"split-block-bloom-filter"`, `"hyperloglog"`, `"count-min-sketch"`, `"minhash"`]
Defined in: [packages/scalar-sketch/src/internal/compatibility.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/internal/compatibility.ts#L4)
# knotkit/scalar-sketch/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeScalarSketchOptions](/reference/knotkit/scalar-sketch/wire/interfaces/serializescalarsketchoptions/)
* [ScalarSketchJsonHashIdentity](/reference/knotkit/scalar-sketch/wire/interfaces/scalarsketchjsonhashidentity/)
* [SplitBlockBloomJson](/reference/knotkit/scalar-sketch/wire/interfaces/splitblockbloomjson/)
* [HyperLogLogJson](/reference/knotkit/scalar-sketch/wire/interfaces/hyperloglogjson/)
* [CountMinJson](/reference/knotkit/scalar-sketch/wire/interfaces/countminjson/)
* [MinHashJson](/reference/knotkit/scalar-sketch/wire/interfaces/minhashjson/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [ScalarSketchJson](/reference/knotkit/scalar-sketch/wire/type-aliases/scalarsketchjson/)
## Functions
[Section titled “Functions”](#functions)
* [serializeScalarSketch](/reference/knotkit/scalar-sketch/wire/functions/serializescalarsketch/)
* [deserializeScalarSketch](/reference/knotkit/scalar-sketch/wire/functions/deserializescalarsketch/)
* [serializeScalarSketchJson](/reference/knotkit/scalar-sketch/wire/functions/serializescalarsketchjson/)
* [deserializeScalarSketchJson](/reference/knotkit/scalar-sketch/wire/functions/deserializescalarsketchjson/)
# deserializeScalarSketch
> **deserializeScalarSketch**(`value`): [`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
Defined in: [packages/scalar-sketch/src/serialization/binary.ts:124](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/binary.ts#L124)
Deserialize exact state from untrusted canonical binary bytes. Shared envelope geometry, family dimensions, and state invariants are checked before mutable typed state is allocated.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
[`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
## Throws
[Section titled “Throws”](#throws)
For malformed envelopes, unsupported scalar-sketch versions, unknown discriminants, or invalid family state.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for invalid hash identities.
# deserializeScalarSketchJson
> **deserializeScalarSketchJson**(`value`): [`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:131](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L131)
Deserialize exact state from an untrusted logical JSON value. Records must have exactly the documented keys as own data properties. State arrays must use `Array.prototype`, have the exact expected length, and contain own, enumerable numeric data elements at every index without holes, enumerable extras, or symbol properties. Non-enumerable string metadata on an array is ignored because it cannot affect logical restoration. Accessors at logical fields or array indices are rejected through descriptors without invocation.
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
## Returns
[Section titled “Returns”](#returns)
[`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
## Throws
[Section titled “Throws”](#throws)
For malformed envelopes, unsupported scalar-sketch versions, unknown discriminants, or invalid family state.
## Throws
[Section titled “Throws”](#throws-1)
From `knotkit/hash` for invalid hash identities.
# serializeScalarSketch
> **serializeScalarSketch**(`sketch`, `options?`): `Uint8Array`
Defined in: [packages/scalar-sketch/src/serialization/binary.ts:103](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/binary.ts#L103)
Serialize exact scalar-sketch state into canonical binary bytes.
## Parameters
[Section titled “Parameters”](#parameters)
### sketch
[Section titled “sketch”](#sketch)
[`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
### options?
[Section titled “options?”](#options)
[`SerializeScalarSketchOptions`](/reference/knotkit/scalar-sketch/wire/interfaces/serializescalarsketchoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_STRUCTURE`, `WRONG_FAMILY`, or `STATE_TOO_LARGE` when the value cannot be serialized.
# serializeScalarSketchJson
> **serializeScalarSketchJson**(`sketch`): [`ScalarSketchJson`](/reference/knotkit/scalar-sketch/wire/type-aliases/scalarsketchjson/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L69)
Serialize exact scalar-sketch state into the stable logical JSON shape. Object keys are inserted in the documented canonical order, while unsigned 64-bit values use canonical decimal strings.
## Parameters
[Section titled “Parameters”](#parameters)
### sketch
[Section titled “sketch”](#sketch)
[`ScalarSketch`](/reference/knotkit/scalar-sketch/type-aliases/scalarsketch/)
## Returns
[Section titled “Returns”](#returns)
[`ScalarSketchJson`](/reference/knotkit/scalar-sketch/wire/type-aliases/scalarsketchjson/)
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_STRUCTURE` or `WRONG_FAMILY` when the value was not produced by this package.
# CountMinJson
Defined in: [packages/scalar-sketch/src/serialization/json.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L46)
## Extends
[Section titled “Extends”](#extends)
* `ScalarSketchJsonBase`
## Properties
[Section titled “Properties”](#properties)
### wireVersion
[Section titled “wireVersion”](#wireversion)
> `readonly` **wireVersion**: `1`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L27)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`ScalarSketchJsonBase.wireVersion`
***
### producerVersion
[Section titled “producerVersion”](#producerversion)
> `readonly` **producerVersion**: `string`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L28)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`ScalarSketchJsonBase.producerVersion`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L29)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`ScalarSketchJsonBase.scalarKind`
***
### hash
[Section titled “hash”](#hash)
> `readonly` **hash**: [`ScalarSketchJsonHashIdentity`](/reference/knotkit/scalar-sketch/wire/interfaces/scalarsketchjsonhashidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L30)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`ScalarSketchJsonBase.hash`
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L31)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`ScalarSketchJsonBase.seedSchedule`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"count-min-sketch"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L47)
***
### config
[Section titled “config”](#config)
> `readonly` **config**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L48)
#### width
[Section titled “width”](#width)
> `readonly` **width**: `number`
#### depth
[Section titled “depth”](#depth)
> `readonly` **depth**: `number`
#### counterBits
[Section titled “counterBits”](#counterbits)
> `readonly` **counterBits**: `32`
***
### state
[Section titled “state”](#state)
> `readonly` **state**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L49)
#### totalWeight
[Section titled “totalWeight”](#totalweight)
> `readonly` **totalWeight**: `number`
#### counters
[Section titled “counters”](#counters)
> `readonly` **counters**: readonly `number`\[]
# HyperLogLogJson
Defined in: [packages/scalar-sketch/src/serialization/json.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L40)
## Extends
[Section titled “Extends”](#extends)
* `ScalarSketchJsonBase`
## Properties
[Section titled “Properties”](#properties)
### wireVersion
[Section titled “wireVersion”](#wireversion)
> `readonly` **wireVersion**: `1`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L27)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`ScalarSketchJsonBase.wireVersion`
***
### producerVersion
[Section titled “producerVersion”](#producerversion)
> `readonly` **producerVersion**: `string`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L28)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`ScalarSketchJsonBase.producerVersion`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L29)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`ScalarSketchJsonBase.scalarKind`
***
### hash
[Section titled “hash”](#hash)
> `readonly` **hash**: [`ScalarSketchJsonHashIdentity`](/reference/knotkit/scalar-sketch/wire/interfaces/scalarsketchjsonhashidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L30)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`ScalarSketchJsonBase.hash`
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L31)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`ScalarSketchJsonBase.seedSchedule`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"hyperloglog"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L41)
***
### config
[Section titled “config”](#config)
> `readonly` **config**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L42)
#### precision
[Section titled “precision”](#precision)
> `readonly` **precision**: `number`
#### indexBits
[Section titled “indexBits”](#indexbits)
> `readonly` **indexBits**: `"high"`
#### rankBits
[Section titled “rankBits”](#rankbits)
> `readonly` **rankBits**: `"remaining"`
***
### state
[Section titled “state”](#state)
> `readonly` **state**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L43)
#### registers
[Section titled “registers”](#registers)
> `readonly` **registers**: readonly `number`\[]
# MinHashJson
Defined in: [packages/scalar-sketch/src/serialization/json.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L52)
## Extends
[Section titled “Extends”](#extends)
* `ScalarSketchJsonBase`
## Properties
[Section titled “Properties”](#properties)
### wireVersion
[Section titled “wireVersion”](#wireversion)
> `readonly` **wireVersion**: `1`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L27)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`ScalarSketchJsonBase.wireVersion`
***
### producerVersion
[Section titled “producerVersion”](#producerversion)
> `readonly` **producerVersion**: `string`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L28)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`ScalarSketchJsonBase.producerVersion`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L29)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`ScalarSketchJsonBase.scalarKind`
***
### hash
[Section titled “hash”](#hash)
> `readonly` **hash**: [`ScalarSketchJsonHashIdentity`](/reference/knotkit/scalar-sketch/wire/interfaces/scalarsketchjsonhashidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L30)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`ScalarSketchJsonBase.hash`
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L31)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`ScalarSketchJsonBase.seedSchedule`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"minhash"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L53)
***
### config
[Section titled “config”](#config)
> `readonly` **config**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L54)
#### signatureSize
[Section titled “signatureSize”](#signaturesize)
> `readonly` **signatureSize**: `number`
***
### state
[Section titled “state”](#state)
> `readonly` **state**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L55)
#### observed
[Section titled “observed”](#observed)
> `readonly` **observed**: `boolean`
#### signatureWords
[Section titled “signatureWords”](#signaturewords)
> `readonly` **signatureWords**: readonly `number`\[]
# ScalarSketchJsonHashIdentity
Defined in: [packages/scalar-sketch/src/serialization/json.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L20)
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"xxh64"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L21)
***
### version
[Section titled “version”](#version)
> `readonly` **version**: `"0.1.0"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L22)
***
### seed
[Section titled “seed”](#seed)
> `readonly` **seed**: `string`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L23)
# SerializeScalarSketchOptions
Defined in: [packages/scalar-sketch/src/serialization/binary.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/binary.ts#L69)
Options for canonical binary serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/scalar-sketch/src/serialization/binary.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/binary.ts#L71)
Include a CRC-32 integrity section for accidental corruption detection.
# SplitBlockBloomJson
Defined in: [packages/scalar-sketch/src/serialization/json.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L34)
## Extends
[Section titled “Extends”](#extends)
* `ScalarSketchJsonBase`
## Properties
[Section titled “Properties”](#properties)
### wireVersion
[Section titled “wireVersion”](#wireversion)
> `readonly` **wireVersion**: `1`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L27)
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
`ScalarSketchJsonBase.wireVersion`
***
### producerVersion
[Section titled “producerVersion”](#producerversion)
> `readonly` **producerVersion**: `string`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L28)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
`ScalarSketchJsonBase.producerVersion`
***
### scalarKind
[Section titled “scalarKind”](#scalarkind)
> `readonly` **scalarKind**: `"string"` | `"uint32"` | `"uint64"` | `"bytes"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L29)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
`ScalarSketchJsonBase.scalarKind`
***
### hash
[Section titled “hash”](#hash)
> `readonly` **hash**: [`ScalarSketchJsonHashIdentity`](/reference/knotkit/scalar-sketch/wire/interfaces/scalarsketchjsonhashidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L30)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-3)
`ScalarSketchJsonBase.hash`
***
### seedSchedule
[Section titled “seedSchedule”](#seedschedule)
> `readonly` **seedSchedule**: [`SeedScheduleIdentity`](/reference/knotkit/scalar-sketch/type-aliases/seedscheduleidentity/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L31)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-4)
`ScalarSketchJsonBase.seedSchedule`
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"split-block-bloom-filter"`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L35)
***
### config
[Section titled “config”](#config)
> `readonly` **config**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L36)
#### blockCount
[Section titled “blockCount”](#blockcount)
> `readonly` **blockCount**: `number`
***
### state
[Section titled “state”](#state)
> `readonly` **state**: `object`
Defined in: [packages/scalar-sketch/src/serialization/json.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L37)
#### updateCount
[Section titled “updateCount”](#updatecount)
> `readonly` **updateCount**: `string`
#### words
[Section titled “words”](#words)
> `readonly` **words**: readonly `number`\[]
# ScalarSketchJson
> **ScalarSketchJson** = [`SplitBlockBloomJson`](/reference/knotkit/scalar-sketch/wire/interfaces/splitblockbloomjson/) | [`HyperLogLogJson`](/reference/knotkit/scalar-sketch/wire/interfaces/hyperloglogjson/) | [`CountMinJson`](/reference/knotkit/scalar-sketch/wire/interfaces/countminjson/) | [`MinHashJson`](/reference/knotkit/scalar-sketch/wire/interfaces/minhashjson/)
Defined in: [packages/scalar-sketch/src/serialization/json.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/scalar-sketch/src/serialization/json.ts#L59)
The stable, inspectable logical JSON form. It is a parsed value, not JSON text.
# knotkit/snapshot-set
## Classes
[Section titled “Classes”](#classes)
* [SnapshotSetParseError](/reference/knotkit/snapshot-set/classes/snapshotsetparseerror/)
* [SnapshotSetInvalidInputError](/reference/knotkit/snapshot-set/classes/snapshotsetinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SnapshotSetFactory](/reference/knotkit/snapshot-set/interfaces/snapshotsetfactory/)
* [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [SnapshotSetInvalidInputErrorCode](/reference/knotkit/snapshot-set/type-aliases/snapshotsetinvalidinputerrorcode/)
* [SnapshotSetParseErrorCode](/reference/knotkit/snapshot-set/type-aliases/snapshotsetparseerrorcode/)
* [SnapshotSetErrorCode](/reference/knotkit/snapshot-set/type-aliases/snapshotseterrorcode/)
* [SnapshotSetKind](/reference/knotkit/snapshot-set/type-aliases/snapshotsetkind/)
## Variables
[Section titled “Variables”](#variables)
* [SNAPSHOT_SET_INVALID_INPUT_ERROR_CODES](/reference/knotkit/snapshot-set/variables/snapshot_set_invalid_input_error_codes/)
* [SNAPSHOT_SET_PARSE_ERROR_CODES](/reference/knotkit/snapshot-set/variables/snapshot_set_parse_error_codes/)
* [SNAPSHOT_SET_ERROR_CODES](/reference/knotkit/snapshot-set/variables/snapshot_set_error_codes/)
* [\_\_SNAPSHOT_SET_LAYOUTS](/reference/knotkit/snapshot-set/variables/snapshot_set_layouts/)
* [SNAPSHOT_SET_KINDS](/reference/knotkit/snapshot-set/variables/snapshot_set_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [snapshotSet](/reference/knotkit/snapshot-set/functions/snapshotset/)
# SnapshotSetInvalidInputError
Defined in: [packages/snapshot-set/src/errors.ts:68](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L68)
Thrown when a caller passes a snapshot id `createSnapshot()` never minted, or a `SnapshotSet` this module never produced.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`SnapshotSetInvalidInputErrorCode`](/reference/knotkit/snapshot-set/type-aliases/snapshotsetinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new SnapshotSetInvalidInputError**(`code`, `message`): `SnapshotSetInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"` | `"FOREIGN_SNAPSHOT_SET"` | `"SNAPSHOT_ID_NOT_MINTED"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`SnapshotSetInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"` | `"FOREIGN_SNAPSHOT_SET"` | `"SNAPSHOT_ID_NOT_MINTED"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/snapshot-set"`
Defined in: [packages/snapshot-set/src/errors.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L69)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# SnapshotSetParseError
Defined in: [packages/snapshot-set/src/errors.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L63)
Thrown when decoding a `SerializedSnapshotSet` that is malformed or fails validation.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`SnapshotSetParseErrorCode`](/reference/knotkit/snapshot-set/type-aliases/snapshotsetparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new SnapshotSetParseError**(`code`, `message`): `SnapshotSetParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"DUPLICATE_VALUE"` | `"MISSING_VALUES"` | `"MISSING_HISTORY"` | `"VALUES_HISTORY_LENGTH_MISMATCH"` | `"INVALID_SNAPSHOTS"` | `"INVALID_VERSION"` | `"INVALID_HISTORY_ENTRY"` | `"EMPTY_HISTORY_ENTRY"` | `"HISTORY_NOT_STRICTLY_INCREASING"` | `"HISTORY_EXCEEDS_VERSION"` | `"HISTORY_ORDER_VIOLATION"` | `"SNAPSHOT_EXCEEDS_VERSION"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`SnapshotSetParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"DUPLICATE_VALUE"` | `"MISSING_VALUES"` | `"MISSING_HISTORY"` | `"VALUES_HISTORY_LENGTH_MISMATCH"` | `"INVALID_SNAPSHOTS"` | `"INVALID_VERSION"` | `"INVALID_HISTORY_ENTRY"` | `"EMPTY_HISTORY_ENTRY"` | `"HISTORY_NOT_STRICTLY_INCREASING"` | `"HISTORY_EXCEEDS_VERSION"` | `"HISTORY_ORDER_VIOLATION"` | `"SNAPSHOT_EXCEEDS_VERSION"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/snapshot-set"`
Defined in: [packages/snapshot-set/src/errors.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L64)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# snapshotSet
> **snapshotSet**<`T`>(`values?`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/snapshot-set.ts:407](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L407)
Create a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/) backed by one toggle-version history per value, optionally pre-populated from an iterable.
Diverges from `knotkit/disjoint-set`’s growable factories: a duplicate value in the initial iterable is a silent no-op, matching `add`’s no-op-on-present rule, rather than a throw.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values?
[Section titled “values?”](#values)
`Iterable`<`T`, `any`, `any`>
Values to insert, in iteration order.
## Returns
[Section titled “Returns”](#returns)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
# SnapshotSet
Defined in: [packages/snapshot-set/src/snapshot-set.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L57)
A mutable set backed by per-value toggle-version history.
Values are compared with `SameValueZero`, the same equality that `Map` and `Set` use. `NaN` equals itself, and `0` equals `-0`.
`values()` walks values in first-registration order — the order a value was first added, not `Set`’s reinsertion order. A value that is removed and later re-added keeps its original position, because its registry index never changes.
`createSnapshot()` mints an id denoting the set’s state at the moment of the call. Later mutations never change any answer derived from an id minted at or before that call — that is the one invariant the whole design exists to hold. Only ids `createSnapshot()` returned are valid; `hasAt` and `valuesAt` throw for anything else, including a version number the structure passed through but never handed out as a snapshot id.
All implementations mutate in place.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"version-chain"`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L59)
Stable identifier for the implementation’s storage layout.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L61)
Number of values currently present. O(1).
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`value`) => `boolean`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L63)
Return `true` when the value is currently present. O(1) average.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`T`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
***
### add
[Section titled “add”](#add)
> `readonly` **add**: (`value`) => `boolean`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L71)
Insert a value. O(1) amortized.
A no-op when the value is already present.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value-1)
`T`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
`true` when the value was not already present.
***
### delete
[Section titled “delete”](#delete)
> `readonly` **delete**: (`value`) => `boolean`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:79](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L79)
Delete a value. O(1) average.
A no-op when the value is not present.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### value
[Section titled “value”](#value-2)
`T`
#### Returns
[Section titled “Returns”](#returns-2)
`boolean`
`true` when the value was present and is now removed.
***
### values
[Section titled “values”](#values)
> `readonly` **values**: () => `IterableIterator`<`T`>
Defined in: [packages/snapshot-set/src/snapshot-set.ts:87](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L87)
Iterate over the values present when the call was made, in first-registration order. O(1) per step, O(n) total.
The iterator covers the values present at call time; mutating the set while iterating does not extend the walk.
#### Returns
[Section titled “Returns”](#returns-3)
`IterableIterator`<`T`>
***
### createSnapshot
[Section titled “createSnapshot”](#createsnapshot)
> `readonly` **createSnapshot**: () => `number`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:97](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L97)
Mint an id denoting the set’s state at this moment. O(1); nothing is copied.
Shares its counter with `add`/`delete`, so two `createSnapshot()` calls with no intervening mutation return different ids that answer identically for every value. Ids are strictly increasing across the structure’s lifetime.
#### Returns
[Section titled “Returns”](#returns-4)
`number`
***
### hasAt
[Section titled “hasAt”](#hasat)
> `readonly` **hasAt**: (`id`, `value`) => `boolean`
Defined in: [packages/snapshot-set/src/snapshot-set.ts:104](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L104)
Return `true` when the value was present at the given snapshot. O(log h), where h is the number of times that value has toggled.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### id
[Section titled “id”](#id)
`number`
##### value
[Section titled “value”](#value-3)
`T`
#### Returns
[Section titled “Returns”](#returns-5)
`boolean`
#### Throws
[Section titled “Throws”](#throws)
When `id` was never returned by `createSnapshot()`.
***
### valuesAt
[Section titled “valuesAt”](#valuesat)
> `readonly` **valuesAt**: (`id`) => `IterableIterator`<`T`>
Defined in: [packages/snapshot-set/src/snapshot-set.ts:122](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L122)
Iterate over the values present at the given snapshot, in first-registration order. O(r \* log h) total, where r is the number of values registered at or before the snapshot and h is a given value’s toggle count.
This cost is proportional to how many values had been *registered* by that snapshot, not to how many the snapshot’s result actually contains — an old snapshot on a set that has since churned through many distinct values still pays for every value registered before it, including ones long removed by then.
The iterator covers the registry prefix that existed when the call was made; mutating the set while iterating does not change the walk.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### id
[Section titled “id”](#id-1)
`number`
#### Returns
[Section titled “Returns”](#returns-6)
`IterableIterator`<`T`>
#### Throws
[Section titled “Throws”](#throws-1)
When `id` was never returned by `createSnapshot()`.
# SnapshotSetFactory
Defined in: [packages/snapshot-set/src/layouts.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/layouts.ts#L4)
Factory signature shared by every snapshot-set layout.
> **SnapshotSetFactory**<`T`>(`values?`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/layouts.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/layouts.ts#L5)
Factory signature shared by every snapshot-set layout.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### values?
[Section titled “values?”](#values)
`Iterable`<`T`, `any`, `any`>
## Returns
[Section titled “Returns”](#returns)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
# SnapshotSetErrorCode
> **SnapshotSetErrorCode** = [`SnapshotSetInvalidInputErrorCode`](/reference/knotkit/snapshot-set/type-aliases/snapshotsetinvalidinputerrorcode/) | [`SnapshotSetParseErrorCode`](/reference/knotkit/snapshot-set/type-aliases/snapshotsetparseerrorcode/)
Defined in: [packages/snapshot-set/src/errors.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L55)
A machine-readable error code emitted by `knotkit/snapshot-set`.
# SnapshotSetInvalidInputErrorCode
> **SnapshotSetInvalidInputErrorCode** = *typeof* [`SNAPSHOT_SET_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/snapshot-set/variables/snapshot_set_invalid_input_error_codes/)\[`number`]
Defined in: [packages/snapshot-set/src/errors.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L49)
# SnapshotSetKind
> **SnapshotSetKind** = *typeof* [`SNAPSHOT_SET_KINDS`](/reference/knotkit/snapshot-set/variables/snapshot_set_kinds/)\[`number`]
Defined in: [packages/snapshot-set/src/snapshot-set.ts:136](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L136)
Storage layouts provided by this package. Only `'version-chain'` ships today.
# SnapshotSetParseErrorCode
> **SnapshotSetParseErrorCode** = *typeof* [`SNAPSHOT_SET_PARSE_ERROR_CODES`](/reference/knotkit/snapshot-set/variables/snapshot_set_parse_error_codes/)\[`number`]
Defined in: [packages/snapshot-set/src/errors.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L52)
A machine-readable parse code emitted by `knotkit/snapshot-set`.
# SNAPSHOT_SET_ERROR_CODES
> `const` **SNAPSHOT_SET_ERROR_CODES**: readonly [`SnapshotSetErrorCode`](/reference/knotkit/snapshot-set/type-aliases/snapshotseterrorcode/)\[]
Defined in: [packages/snapshot-set/src/errors.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L58)
Every code emitted by `knotkit/snapshot-set`, in stable category order.
# SNAPSHOT_SET_INVALID_INPUT_ERROR_CODES
> `const` **SNAPSHOT_SET_INVALID_INPUT_ERROR_CODES**: readonly \[`"FOREIGN_SNAPSHOT_SET"`, `"SNAPSHOT_ID_NOT_MINTED"`, `"MISSING_ELEMENT_CODEC"`, `"INVALID_CODEC_RESULT"`, `"NON_INJECTIVE_CODEC"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/snapshot-set/src/errors.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L7)
The canonical, ordered list of machine-readable error codes emitted by `knotkit/snapshot-set`’s public API.
# SNAPSHOT_SET_KINDS
> `const` **SNAPSHOT_SET_KINDS**: readonly \[`"version-chain"`]
Defined in: [packages/snapshot-set/src/snapshot-set.ts:133](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/snapshot-set.ts#L133)
Every storage layout this package provides, as a runtime value. Only `'version-chain'` ships today.
A single-entry list still earns its keep: it makes the enumeration uniform with the other Knotkit packages, so a caller sweeping layouts writes the same code here, and it gives a second layout one obvious place to land.
# __SNAPSHOT_SET_LAYOUTS
> `const` **\_\_SNAPSHOT_SET_LAYOUTS**: `Readonly`<`Record`<[`SnapshotSetKind`](/reference/knotkit/snapshot-set/type-aliases/snapshotsetkind/), [`SnapshotSetFactory`](/reference/knotkit/snapshot-set/interfaces/snapshotsetfactory/)>>
Defined in: [packages/snapshot-set/src/layouts.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/layouts.ts#L9)
Every snapshot-set layout, keyed by the `kind` its factory reports.
# SNAPSHOT_SET_PARSE_ERROR_CODES
> `const` **SNAPSHOT_SET_PARSE_ERROR_CODES**: readonly \[`"INVALID_SHAPE"`, `"UNSUPPORTED_SCHEMA_VERSION"`, `"UNKNOWN_KIND"`, `"MISSING_VALUES"`, `"MISSING_HISTORY"`, `"VALUES_HISTORY_LENGTH_MISMATCH"`, `"INVALID_SNAPSHOTS"`, `"INVALID_VERSION"`, `"INVALID_HISTORY_ENTRY"`, `"EMPTY_HISTORY_ENTRY"`, `"HISTORY_NOT_STRICTLY_INCREASING"`, `"HISTORY_EXCEEDS_VERSION"`, `"HISTORY_ORDER_VIOLATION"`, `"SNAPSHOT_EXCEEDS_VERSION"`, `"DUPLICATE_VALUE"`, `"INVALID_VALUE"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`, `"INVALID_PACKAGE_HEADER"`]
Defined in: [packages/snapshot-set/src/errors.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/errors.ts#L17)
Codes carried specifically by [SnapshotSetParseError](/reference/knotkit/snapshot-set/classes/snapshotsetparseerror/).
# knotkit/snapshot-set/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeSnapshotSetOptions](/reference/knotkit/snapshot-set/wire/interfaces/serializesnapshotsetoptions/)
* [DeserializeSnapshotSetOptions](/reference/knotkit/snapshot-set/wire/interfaces/deserializesnapshotsetoptions/)
* [SerializedSnapshotSet](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/)
* [DeserializeSnapshotSetJsonOptions](/reference/knotkit/snapshot-set/wire/interfaces/deserializesnapshotsetjsonoptions/)
## Variables
[Section titled “Variables”](#variables)
* [SNAPSHOT_SET_MAX_DECODE_VALUES](/reference/knotkit/snapshot-set/wire/variables/snapshot_set_max_decode_values/)
* [SNAPSHOT_SET_MAX_DECODE_TOGGLES](/reference/knotkit/snapshot-set/wire/variables/snapshot_set_max_decode_toggles/)
* [SNAPSHOT_SET_MAX_DECODE_SNAPSHOTS](/reference/knotkit/snapshot-set/wire/variables/snapshot_set_max_decode_snapshots/)
## Functions
[Section titled “Functions”](#functions)
* [serializeSnapshotSet](/reference/knotkit/snapshot-set/wire/functions/serializesnapshotset/)
* [deserializeSnapshotSet](/reference/knotkit/snapshot-set/wire/functions/deserializesnapshotset/)
* [serializeSnapshotSetJson](/reference/knotkit/snapshot-set/wire/functions/serializesnapshotsetjson/)
* [deserializeSnapshotSetJson](/reference/knotkit/snapshot-set/wire/functions/deserializesnapshotsetjson/)
# deserializeSnapshotSet
> **deserializeSnapshotSet**<`T`>(`value`, `options`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/serialization/binary.ts:160](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L160)
Restore a binary snapshot set after validating all counts, histories, snapshot identities, codec results, and duplicate values in staging data.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
### options
[Section titled “options”](#options)
[`DeserializeSnapshotSetOptions`](/reference/knotkit/snapshot-set/wire/interfaces/deserializesnapshotsetoptions/)<`T`>
## Returns
[Section titled “Returns”](#returns)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC` when `options.codec` is absent: supplying the codec is a caller contract, not a property of the bytes.
## Throws
[Section titled “Throws”](#throws-1)
For malformed bytes, unsupported versions, invalid histories, duplicate values, or decode-budget violations.
# deserializeSnapshotSetJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializeSnapshotSetJson**<`T`>(`serialized`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/serialization/json.ts:177](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L177)
Rebuild a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/) from a [SerializedSnapshotSet](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/). O(k + m) time, where k is the number of registered values and m is the total number of toggle entries.
A round trip through `serializeSnapshotSetJson` and `deserializeSnapshotSetJson` preserves `kind`, `size`, `values()` order, and every `hasAt`/`valuesAt` answer for every id minted before serialization — including ids the caller held onto. A further `createSnapshot()` on the restored structure mints an id greater than every restored id, because the version counter is restored exactly, not recomputed by replaying `add`/`delete`.
Untyped input produces a `SnapshotSet`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### T
[Section titled “T”](#t)
`T`
### Parameters
[Section titled “Parameters”](#parameters)
#### serialized
[Section titled “serialized”](#serialized)
[`SerializedSnapshotSet`](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/)<`T`>
The structure to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
### Throws
[Section titled “Throws”](#throws)
When the serialized shape is malformed: a non-object payload, an unknown `kind`, a `values`/`history` length mismatch, a version or toggle-version entry that is not a non-negative safe integer, a history entry that is empty or not strictly increasing, a history or snapshot entry above `version`, a value’s first toggle version not strictly greater than the previous value’s, a duplicate value, or (with `options.isValue` supplied) a value that fails validation. Distinguish causes with `error.code`, one of SnapshotSetErrorCode.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializeSnapshotSetJson**<`T`>(`serialized`, `options`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/serialization/json.ts:178](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L178)
Rebuild a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/) from a [SerializedSnapshotSet](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/). O(k + m) time, where k is the number of registered values and m is the total number of toggle entries.
A round trip through `serializeSnapshotSetJson` and `deserializeSnapshotSetJson` preserves `kind`, `size`, `values()` order, and every `hasAt`/`valuesAt` answer for every id minted before serialization — including ids the caller held onto. A further `createSnapshot()` on the restored structure mints an id greater than every restored id, because the version counter is restored exactly, not recomputed by replaying `add`/`delete`.
Untyped input produces a `SnapshotSet`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### T
[Section titled “T”](#t-1)
`T`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### serialized
[Section titled “serialized”](#serialized-1)
`unknown`
The structure to restore, either statically typed or decoded as `unknown`.
#### options
[Section titled “options”](#options)
[`DeserializeSnapshotSetJsonOptions`](/reference/knotkit/snapshot-set/wire/interfaces/deserializesnapshotsetjsonoptions/)<`T`>
Runtime decoding options for untyped input.
### Returns
[Section titled “Returns”](#returns-1)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
### Throws
[Section titled “Throws”](#throws-1)
When the serialized shape is malformed: a non-object payload, an unknown `kind`, a `values`/`history` length mismatch, a version or toggle-version entry that is not a non-negative safe integer, a history entry that is empty or not strictly increasing, a history or snapshot entry above `version`, a value’s first toggle version not strictly greater than the previous value’s, a duplicate value, or (with `options.isValue` supplied) a value that fails validation. Distinguish causes with `error.code`, one of SnapshotSetErrorCode.
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializeSnapshotSetJson**(`serialized`): [`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`unknown`>
Defined in: [packages/snapshot-set/src/serialization/json.ts:182](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L182)
Rebuild a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/) from a [SerializedSnapshotSet](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/). O(k + m) time, where k is the number of registered values and m is the total number of toggle entries.
A round trip through `serializeSnapshotSetJson` and `deserializeSnapshotSetJson` preserves `kind`, `size`, `values()` order, and every `hasAt`/`valuesAt` answer for every id minted before serialization — including ids the caller held onto. A further `createSnapshot()` on the restored structure mints an id greater than every restored id, because the version counter is restored exactly, not recomputed by replaying `add`/`delete`.
Untyped input produces a `SnapshotSet`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Parameters
[Section titled “Parameters”](#parameters-2)
#### serialized
[Section titled “serialized”](#serialized-2)
`unknown`
The structure to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-2)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`unknown`>
### Throws
[Section titled “Throws”](#throws-2)
When the serialized shape is malformed: a non-object payload, an unknown `kind`, a `values`/`history` length mismatch, a version or toggle-version entry that is not a non-negative safe integer, a history entry that is empty or not strictly increasing, a history or snapshot entry above `version`, a value’s first toggle version not strictly greater than the previous value’s, a duplicate value, or (with `options.isValue` supplied) a value that fails validation. Distinguish causes with `error.code`, one of SnapshotSetErrorCode.
# serializeSnapshotSet
> **serializeSnapshotSet**<`T`>(`set`, `codec`, `options?`): `Uint8Array`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:91](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L91)
Serialize exact snapshot identity, version, value order, and toggle history into canonical binary bytes.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### set
[Section titled “set”](#set)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`T`>
### options?
[Section titled “options?”](#options)
[`SerializeSnapshotSetOptions`](/reference/knotkit/snapshot-set/wire/interfaces/serializesnapshotsetoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the state cannot be represented safely.
# serializeSnapshotSetJson
> **serializeSnapshotSetJson**<`T`>(`set`): [`SerializedSnapshotSet`](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/)<`T`>
Defined in: [packages/snapshot-set/src/serialization/json.ts:71](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L71)
Capture a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/) as a [SerializedSnapshotSet](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/). O(k + m) time and space, where k is the number of registered values and m is the total number of effective mutations recorded across their histories — a direct dump of what is already stored, no search involved.
Every registered value is captured, including ones currently absent, and every minted snapshot id is captured, so a restored structure answers `has`, `hasAt`, `values`, and `valuesAt` identically to the original — including for ids the caller already held before calling `serializeSnapshotSetJson`.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### set
[Section titled “set”](#set)
[`SnapshotSet`](/reference/knotkit/snapshot-set/interfaces/snapshotset/)<`T`>
## Returns
[Section titled “Returns”](#returns)
[`SerializedSnapshotSet`](/reference/knotkit/snapshot-set/wire/interfaces/serializedsnapshotset/)<`T`>
# DeserializeSnapshotSetJsonOptions
Defined in: [packages/snapshot-set/src/serialization/json.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L55)
Runtime decoding options for data whose value type is not yet known.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### isValue
[Section titled “isValue”](#isvalue)
> `readonly` **isValue**: (`value`) => `value is T`
Defined in: [packages/snapshot-set/src/serialization/json.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L57)
Prove the type of every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is T`
# DeserializeSnapshotSetOptions
Defined in: [packages/snapshot-set/src/serialization/binary.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L48)
Runtime inputs needed to decode a snapshot set’s generic value run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### codec
[Section titled “codec”](#codec)
> `readonly` **codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`T`>
Defined in: [packages/snapshot-set/src/serialization/binary.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L50)
Codec matching the one used to serialize values.
***
### isValue?
[Section titled “isValue?”](#isvalue)
> `readonly` `optional` **isValue?**: (`value`) => `value is T`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L52)
Optional validation applied to every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is T`
# SerializedSnapshotSet
Defined in: [packages/snapshot-set/src/serialization/json.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L39)
A plain, inert description of a [SnapshotSet](/reference/knotkit/snapshot-set/interfaces/snapshotset/). It holds no behavior and no reference to the structure it came from, so it can be stored, compared, structurally cloned, or sent through `postMessage`. It survives `JSON.stringify` when the values themselves do.
`values` lists every value ever registered, in first-registration order, including values currently absent — a value’s `history` alone determines whether it is present at any given version, so reconstructing that requires every registered value, not just the current members. `history[i]` is the strictly increasing toggle-version list for `values[i]`. `snapshots` is every id `createSnapshot()` has minted, ascending. `version` is the current version counter.
Serialization here is **faithful, not canonical**: two structures with identical observable behavior can serialize differently if they took different mutation paths. An `add` followed by a `delete` of the same value between two snapshots leaves two toggle entries behind that a canonicalized form would collapse away, but canonicalizing would mean renumbering versions — and a caller may be holding an id minted under the old numbering. `knotkit/disjoint-set`’s serialization is canonical instead, because it exposes no ids: nothing constrains it to preserve a numbering scheme, so two structures with the same partition always serialize identically.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### T
[Section titled “T”](#t)
`T`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/snapshot-set/src/serialization/json.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L41)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"version-chain"`
Defined in: [packages/snapshot-set/src/serialization/json.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L43)
The storage layout to restore. Only `'version-chain'` exists today.
***
### values
[Section titled “values”](#values)
> `readonly` **values**: readonly `T`\[]
Defined in: [packages/snapshot-set/src/serialization/json.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L45)
Every registered value, in first-registration order, including currently absent ones.
***
### history
[Section titled “history”](#history)
> `readonly` **history**: readonly (readonly `number`\[])\[]
Defined in: [packages/snapshot-set/src/serialization/json.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L47)
The toggle-version history of the value at the same position, strictly increasing.
***
### snapshots
[Section titled “snapshots”](#snapshots)
> `readonly` **snapshots**: readonly `number`\[]
Defined in: [packages/snapshot-set/src/serialization/json.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L49)
Every id `createSnapshot()` has minted, ascending.
***
### version
[Section titled “version”](#version)
> `readonly` **version**: `number`
Defined in: [packages/snapshot-set/src/serialization/json.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/json.ts#L51)
The current version counter.
# SerializeSnapshotSetOptions
Defined in: [packages/snapshot-set/src/serialization/binary.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L42)
Optional behavior for binary snapshot-set serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L44)
Include a CRC-32 integrity section for accidental corruption detection.
# SNAPSHOT_SET_MAX_DECODE_SNAPSHOTS
> `const` **SNAPSHOT_SET_MAX_DECODE_SNAPSHOTS**: `1000000` = `1_000_000`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L39)
Maximum minted snapshot ids staged by a snapshot-set decoder.
# SNAPSHOT_SET_MAX_DECODE_TOGGLES
> `const` **SNAPSHOT_SET_MAX_DECODE_TOGGLES**: `4000000` = `4_000_000`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L36)
Maximum total toggle entries staged by a snapshot-set decoder.
# SNAPSHOT_SET_MAX_DECODE_VALUES
> `const` **SNAPSHOT_SET_MAX_DECODE_VALUES**: `1000000` = `1_000_000`
Defined in: [packages/snapshot-set/src/serialization/binary.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/snapshot-set/src/serialization/binary.ts#L33)
Maximum number of registered values staged by a snapshot-set decoder.
# knotkit/sorted-block
## Classes
[Section titled “Classes”](#classes)
* [SortedBlockInvalidInputError](/reference/knotkit/sorted-block/classes/sortedblockinvalidinputerror/)
* [SortedBlockParseError](/reference/knotkit/sorted-block/classes/sortedblockparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [RestartPointSortedBlockOptions](/reference/knotkit/sorted-block/interfaces/restartpointsortedblockoptions/)
* [SortedBlock](/reference/knotkit/sorted-block/interfaces/sortedblock/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [SortedBlockInvalidInputErrorCode](/reference/knotkit/sorted-block/type-aliases/sortedblockinvalidinputerrorcode/)
* [SortedBlockParseErrorCode](/reference/knotkit/sorted-block/type-aliases/sortedblockparseerrorcode/)
* [SortedBlockErrorCode](/reference/knotkit/sorted-block/type-aliases/sortedblockerrorcode/)
* [SortedBlockKind](/reference/knotkit/sorted-block/type-aliases/sortedblockkind/)
* [SortedBlockEntry](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)
* [SortedBlockFactory](/reference/knotkit/sorted-block/type-aliases/sortedblockfactory/)
## Variables
[Section titled “Variables”](#variables)
* [SORTED_BLOCK_INVALID_INPUT_ERROR_CODES](/reference/knotkit/sorted-block/variables/sorted_block_invalid_input_error_codes/)
* [SORTED_BLOCK_PARSE_ERROR_CODES](/reference/knotkit/sorted-block/variables/sorted_block_parse_error_codes/)
* [SORTED_BLOCK_ERROR_CODES](/reference/knotkit/sorted-block/variables/sorted_block_error_codes/)
* [\_\_SORTED_BLOCK_LAYOUTS](/reference/knotkit/sorted-block/variables/sorted_block_layouts/)
* [SORTED_BLOCK_KINDS](/reference/knotkit/sorted-block/variables/sorted_block_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [restartPointSortedBlock](/reference/knotkit/sorted-block/functions/restartpointsortedblock/)
# SortedBlockInvalidInputError
Defined in: [packages/sorted-block/src/errors.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L53)
Thrown when a caller passes a restart interval that is not a positive safe integer, an entry or key that is not bytes, entries out of strictly ascending byte order, a range whose end sorts before its start, more entries or bytes than one block addresses, or an object this package did not produce to `serializeSortedBlock`.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`SortedBlockInvalidInputErrorCode`](/reference/knotkit/sorted-block/type-aliases/sortedblockinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new SortedBlockInvalidInputError**(`code`, `message`): `SortedBlockInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_RANGE"` | `"MAX_CAPACITY_EXCEEDED"` | `"INVALID_KEY"` | `"INVALID_RESTART_INTERVAL"` | `"INVALID_ENTRY"` | `"UNSORTED_KEY"` | `"DUPLICATE_KEY"` | `"FOREIGN_SORTED_BLOCK"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`SortedBlockInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_RANGE"` | `"MAX_CAPACITY_EXCEEDED"` | `"INVALID_KEY"` | `"INVALID_RESTART_INTERVAL"` | `"INVALID_ENTRY"` | `"UNSORTED_KEY"` | `"DUPLICATE_KEY"` | `"FOREIGN_SORTED_BLOCK"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/sorted-block"`
Defined in: [packages/sorted-block/src/errors.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L54)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# SortedBlockParseError
Defined in: [packages/sorted-block/src/errors.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L58)
Thrown when decoding a `serializeSortedBlock` artifact that is malformed or internally inconsistent.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`SortedBlockParseErrorCode`](/reference/knotkit/sorted-block/type-aliases/sortedblockparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new SortedBlockParseError**(`code`, `message`): `SortedBlockParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"CORRUPT_BLOCK_PAYLOAD"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`SortedBlockParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"CORRUPT_BLOCK_PAYLOAD"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/sorted-block"`
Defined in: [packages/sorted-block/src/errors.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L59)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# restartPointSortedBlock
> **restartPointSortedBlock**(`entries`, `options?`): [`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
Defined in: [packages/sorted-block/src/restart-point-sorted-block.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/restart-point-sorted-block.ts#L19)
Build an immutable `restart-point` block from entries already in strictly ascending `compareBytes` key order.
Each key is stored as the bytes it does not share with the previous key, except at every `restartInterval`-th entry, a restart point, where it is stored whole. Lookups binary-search the restart keys in place and decode at most `restartInterval` entries forward. Every input byte is copied into one `Uint8Array`, so mutating the caller’s arrays afterwards cannot change the block. Builds in O(total key and value bytes).
## Parameters
[Section titled “Parameters”](#parameters)
### entries
[Section titled “entries”](#entries)
`Iterable`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
### options?
[Section titled “options?”](#options)
[`RestartPointSortedBlockOptions`](/reference/knotkit/sorted-block/interfaces/restartpointsortedblockoptions/)
## Returns
[Section titled “Returns”](#returns)
[`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_RESTART_INTERVAL` when `restartInterval` is not a positive safe integer, `INVALID_ENTRY` when `entries` is not iterable or an entry is not a `[Uint8Array, Uint8Array]` pair, `UNSORTED_KEY` or `DUPLICATE_KEY` when keys do not strictly ascend, and `MAX_CAPACITY_EXCEEDED` when the entries pass 2^32 - 1 bytes or entries, or the runtime refuses the allocation.
# RestartPointSortedBlockOptions
Defined in: [packages/sorted-block/src/sorted-block.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L14)
Options for [SortedBlockFactory](/reference/knotkit/sorted-block/type-aliases/sortedblockfactory/) when it builds a `restart-point` block.
## Properties
[Section titled “Properties”](#properties)
### restartInterval?
[Section titled “restartInterval?”](#restartinterval)
> `readonly` `optional` **restartInterval?**: `number`
Defined in: [packages/sorted-block/src/sorted-block.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L19)
Entries between two restart points, a positive safe integer; `16` when omitted. A restart point stores its key whole, so a smaller interval spends more bytes on keys and on the restart table and scans fewer entries per read.
# SortedBlock
Defined in: [packages/sorted-block/src/sorted-block.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L29)
An immutable sorted key-value block held in one `Uint8Array`.
Keys are distinct and ascend under `compareBytes`. Every read returns fresh copies of the bytes it reports, so a caller can mutate what it receives without changing the block, and the block owns a copy of every byte it was built from. A block never changes after construction, so its iterators never observe a modification.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"restart-point"`
Defined in: [packages/sorted-block/src/sorted-block.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L30)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/sorted-block/src/sorted-block.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L32)
Number of entries.
***
### byteLength
[Section titled “byteLength”](#bytelength)
> `readonly` **byteLength**: `number`
Defined in: [packages/sorted-block/src/sorted-block.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L34)
Bytes of the encoded block payload: entries, restart table, and trailer.
***
### firstKey
[Section titled “firstKey”](#firstkey)
> `readonly` **firstKey**: `Uint8Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/sorted-block/src/sorted-block.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L36)
A copy of the smallest key, or `undefined` for an empty block.
***
### lastKey
[Section titled “lastKey”](#lastkey)
> `readonly` **lastKey**: `Uint8Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/sorted-block/src/sorted-block.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L38)
A copy of the largest key, or `undefined` for an empty block.
***
### get
[Section titled “get”](#get)
> `readonly` **get**: (`key`) => `Uint8Array`<`ArrayBufferLike`> | `undefined`
Defined in: [packages/sorted-block/src/sorted-block.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L44)
A copy of the value stored under `key`, or `undefined` when the block holds no such key.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`Uint8Array`<`ArrayBufferLike`> | `undefined`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_KEY` when `key` is not a `Uint8Array`.
***
### has
[Section titled “has”](#has)
> `readonly` **has**: (`key`) => `boolean`
Defined in: [packages/sorted-block/src/sorted-block.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L50)
Whether the block holds `key`.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### key
[Section titled “key”](#key-1)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`boolean`
#### Throws
[Section titled “Throws”](#throws-1)
With `INVALID_KEY` when `key` is not a `Uint8Array`.
***
### ceiling
[Section titled “ceiling”](#ceiling)
> `readonly` **ceiling**: (`key`) => [`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/) | `undefined`
Defined in: [packages/sorted-block/src/sorted-block.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L57)
A copy of the smallest entry whose key is at or above `key` under `compareBytes`, or `undefined` when every key sorts below it.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### key
[Section titled “key”](#key-2)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-2)
[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/) | `undefined`
#### Throws
[Section titled “Throws”](#throws-2)
With `INVALID_KEY` when `key` is not a `Uint8Array`.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: (…`bounds`) => `IterableIterator`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
Defined in: [packages/sorted-block/src/sorted-block.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L65)
Walk entries in ascending key order: every entry, the open range `[start, +∞)`, or the half-open range `[start, end)`. Bounds are checked when the call is made, not on the first step.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### bounds
[Section titled “bounds”](#bounds)
\[] | \[`start`: `Uint8Array`<`ArrayBufferLike`>] | \[`start`: `Uint8Array`<`ArrayBufferLike`>, `end`: `Uint8Array`<`ArrayBufferLike`>]
#### Returns
[Section titled “Returns”](#returns-3)
`IterableIterator`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
#### Throws
[Section titled “Throws”](#throws-3)
With `INVALID_KEY` when a bound is not a `Uint8Array`, or `INVALID_RANGE` when `end` sorts before `start`.
***
### \[iterator]
[Section titled “\[iterator\]”](#iterator)
> `readonly` **\[iterator]**: () => `IterableIterator`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
Defined in: [packages/sorted-block/src/sorted-block.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L69)
The same function as `entries`: a full walk in ascending key order.
#### Returns
[Section titled “Returns”](#returns-4)
`IterableIterator`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
# SortedBlockEntry
> **SortedBlockEntry** = readonly \[`key`: `Uint8Array`, `value`: `Uint8Array`]
Defined in: [packages/sorted-block/src/sorted-block.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L11)
One key-value pair of a block. Keys are compared by `compareBytes` from `knotkit/key-encoding`.
# SortedBlockErrorCode
> **SortedBlockErrorCode** = [`SortedBlockInvalidInputErrorCode`](/reference/knotkit/sorted-block/type-aliases/sortedblockinvalidinputerrorcode/) | [`SortedBlockParseErrorCode`](/reference/knotkit/sorted-block/type-aliases/sortedblockparseerrorcode/)
Defined in: [packages/sorted-block/src/errors.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L41)
A machine-readable error code emitted by `knotkit/sorted-block`.
# SortedBlockFactory
> **SortedBlockFactory** = (`entries`, `options?`) => [`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
Defined in: [packages/sorted-block/src/sorted-block.ts:73](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L73)
A factory that builds a [SortedBlock](/reference/knotkit/sorted-block/interfaces/sortedblock/) from entries already in strictly ascending key order.
## Parameters
[Section titled “Parameters”](#parameters)
### entries
[Section titled “entries”](#entries)
`Iterable`<[`SortedBlockEntry`](/reference/knotkit/sorted-block/type-aliases/sortedblockentry/)>
### options?
[Section titled “options?”](#options)
[`RestartPointSortedBlockOptions`](/reference/knotkit/sorted-block/interfaces/restartpointsortedblockoptions/)
## Returns
[Section titled “Returns”](#returns)
[`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
# SortedBlockInvalidInputErrorCode
> **SortedBlockInvalidInputErrorCode** = *typeof* [`SORTED_BLOCK_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/sorted-block/variables/sorted_block_invalid_input_error_codes/)\[`number`]
Defined in: [packages/sorted-block/src/errors.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L35)
A machine-readable invalid-input code emitted by `knotkit/sorted-block`.
# SortedBlockKind
> **SortedBlockKind** = *typeof* [`SORTED_BLOCK_KINDS`](/reference/knotkit/sorted-block/variables/sorted_block_kinds/)\[`number`]
Defined in: [packages/sorted-block/src/sorted-block.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L8)
A layout of [SortedBlock](/reference/knotkit/sorted-block/interfaces/sortedblock/), the serializable discriminant its `kind` reports.
# SortedBlockParseErrorCode
> **SortedBlockParseErrorCode** = *typeof* [`SORTED_BLOCK_PARSE_ERROR_CODES`](/reference/knotkit/sorted-block/variables/sorted_block_parse_error_codes/)\[`number`]
Defined in: [packages/sorted-block/src/errors.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L38)
A machine-readable parse code emitted by `knotkit/sorted-block`.
# SORTED_BLOCK_ERROR_CODES
> `const` **SORTED_BLOCK_ERROR_CODES**: readonly [`SortedBlockErrorCode`](/reference/knotkit/sorted-block/type-aliases/sortedblockerrorcode/)\[]
Defined in: [packages/sorted-block/src/errors.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L44)
Every code emitted by `knotkit/sorted-block`, in stable category order.
# SORTED_BLOCK_INVALID_INPUT_ERROR_CODES
> `const` **SORTED_BLOCK_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_RESTART_INTERVAL"`, `"INVALID_ENTRY"`, `"INVALID_KEY"`, `"UNSORTED_KEY"`, `"DUPLICATE_KEY"`, `"INVALID_RANGE"`, `"MAX_CAPACITY_EXCEEDED"`, `"FOREIGN_SORTED_BLOCK"`]
Defined in: [packages/sorted-block/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/sorted-block`.
# SORTED_BLOCK_KINDS
> `const` **SORTED_BLOCK_KINDS**: readonly \[`"restart-point"`]
Defined in: [packages/sorted-block/src/sorted-block.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/sorted-block.ts#L5)
The block layouts this package constructs. `restart-point` is the only one: prefix-compressed entries with a full key every `restartInterval` entries, the layout LevelDB, RocksDB, and SlateDB use for SSTable data and index blocks.
# __SORTED_BLOCK_LAYOUTS
> `const` **\_\_SORTED_BLOCK_LAYOUTS**: `Readonly`<`Record`<[`SortedBlockKind`](/reference/knotkit/sorted-block/type-aliases/sortedblockkind/), [`SortedBlockFactory`](/reference/knotkit/sorted-block/type-aliases/sortedblockfactory/)>>
Defined in: [packages/sorted-block/src/layouts.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/layouts.ts#L10)
Every block layout this package constructs, keyed by the `kind` it reports.
Exported so a property test, a benchmark, or a `problems/*` preset can sweep every layout without naming one. A caller building one block imports `restartPointSortedBlock` directly.
# SORTED_BLOCK_PARSE_ERROR_CODES
> `const` **SORTED_BLOCK_PARSE_ERROR_CODES**: readonly \[`"INVALID_PACKAGE_HEADER"`, `"UNKNOWN_KIND"`, `"CORRUPT_BLOCK_PAYLOAD"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`]
Defined in: [packages/sorted-block/src/errors.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/errors.ts#L16)
Codes carried specifically by [SortedBlockParseError](/reference/knotkit/sorted-block/classes/sortedblockparseerror/).
# knotkit/sorted-block/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeSortedBlockOptions](/reference/knotkit/sorted-block/wire/interfaces/serializesortedblockoptions/)
## Functions
[Section titled “Functions”](#functions)
* [serializeSortedBlock](/reference/knotkit/sorted-block/wire/functions/serializesortedblock/)
* [deserializeSortedBlock](/reference/knotkit/sorted-block/wire/functions/deserializesortedblock/)
# deserializeSortedBlock
> **deserializeSortedBlock**(`bytes`): [`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
Defined in: [packages/sorted-block/src/serialization.ts:95](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/serialization.ts#L95)
Decode bytes written by [serializeSortedBlock](/reference/knotkit/sorted-block/wire/functions/serializesortedblock/).
The payload is validated in full before a block is returned, in O(byte length): the trailer and restart-table geometry, restart offsets that start at 0, strictly ascend, and land on entry boundaries, canonical uint32 varints, entries inside the entries section, a zero shared prefix at every restart point and none longer than the previous key, strictly ascending rebuilt keys, and an entry count equal to the trailer’s. The block owns a copy of the bytes.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
[`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
## Throws
[Section titled “Throws”](#throws)
With `CORRUPT_BLOCK_PAYLOAD` when the payload breaks one of those rules, `INVALID_PACKAGE_HEADER` for a malformed header, `UNKNOWN_KIND` for a kind tag this release does not read, or a shared wire code from `SORTED_BLOCK_PARSE_ERROR_CODES` for a malformed envelope.
# serializeSortedBlock
> **serializeSortedBlock**(`block`, `options?`): `Uint8Array`
Defined in: [packages/sorted-block/src/serialization.ts:64](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/serialization.ts#L64)
Serialize a block into binary bytes that restore the same entries and layout.
The block payload is written unchanged — prefix-compressed entries, the restart table, and the trailer — inside a `knotkit/wire` envelope with a producer version. Runs in O(byteLength).
## Parameters
[Section titled “Parameters”](#parameters)
### block
[Section titled “block”](#block)
[`SortedBlock`](/reference/knotkit/sorted-block/interfaces/sortedblock/)
### options?
[Section titled “options?”](#options)
[`SerializeSortedBlockOptions`](/reference/knotkit/sorted-block/wire/interfaces/serializesortedblockoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_SORTED_BLOCK` when `block` was not produced by this package, or `MAX_CAPACITY_EXCEEDED` when the runtime cannot allocate the artifact.
# SerializeSortedBlockOptions
Defined in: [packages/sorted-block/src/serialization.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/serialization.ts#L50)
Optional behavior for binary block serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/sorted-block/src/serialization.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-block/src/serialization.ts#L52)
Include a CRC-32 integrity section for accidental corruption detection.
# knotkit/sorted-merge
## Functions
[Section titled “Functions”](#functions)
* [mergeSortedAsync](/reference/knotkit/sorted-merge/functions/mergesortedasync/)
* [mergeSorted](/reference/knotkit/sorted-merge/functions/mergesorted/)
# mergeSorted
> **mergeSorted**<`A`>(`order`, `sources`): `Generator`<`A`, `void`, `unknown`>
Defined in: [packages/sorted-merge/src/merge-sorted.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-merge/src/merge-sorted.ts#L40)
Lazily merge a finite collection of independently iterable sorted sources under the same total order. Keeps duplicates. Equal items retain their order within each source, with earlier sources winning ties. Supply a stable order and keep compared values unchanged while the merge is active.
The first advance calls next() once on each source. Each subsequent advance pulls only from the source of the last emitted value. With k sources, setup takes O(k) time and space, and each output after setup takes O(log(k + 1)) time, excluding input reads and comparator cost. Individual sources may be infinite.
On early return or failure, calls return() once on each opened, unfinished iterator that exposes it. Errors from the order and input iterators propagate. A cleanup error surfaces if the merge was otherwise returning normally. When several iterators fail during cleanup, the first error surfaces after all are tried.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### sources
[Section titled “sources”](#sources)
`Iterable`<`Iterable`<`A`, `any`, `any`>>
## Returns
[Section titled “Returns”](#returns)
`Generator`<`A`, `void`, `unknown`>
# mergeSortedAsync
> **mergeSortedAsync**<`A`>(`order`, `sources`): `AsyncGenerator`<`Awaited`<`A`>, `void`, `unknown`>
Defined in: [packages/sorted-merge/src/merge-sorted-async.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sorted-merge/src/merge-sorted-async.ts#L60)
Lazily merge a finite collection of independently iterable sorted sources, async or sync, under the same total order. Keeps duplicates. Equal items retain their order within each source, with earlier sources winning ties. Supply a stable order and keep compared values unchanged while the merge is active.
Each source is opened through `Symbol.asyncIterator` when it has one and through `Symbol.iterator` otherwise, so async streams and in-memory arrays mix freely. Items are compared as the sources produce them; the merge does not await an item that is itself a promise before comparing it. The generator yields its resolved value. A rejected item rejects the advance and triggers source cleanup.
The first advance opens every source in collection order, then awaits each source’s first next() concurrently and waits for all of them to settle. If any of them rejects, no read is still in flight when the merge closes the opened sources, and the rejection from the earliest source in collection order propagates. Each subsequent advance awaits next() only on the source of the last emitted value. With k sources, setup takes O(k) time and space, and each output after setup takes O(log(k + 1)) time, excluding input reads and comparator cost. At most one item per source is buffered. Individual sources may be infinite.
On early return or failure, awaits return() once on each opened, unfinished iterator that exposes it, one at a time in collection order. Errors from the order and input iterators propagate. A cleanup error surfaces if the merge was otherwise returning normally. When several iterators fail during cleanup, the first error surfaces after all are tried.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### A
[Section titled “A”](#a)
`A`
## Parameters
[Section titled “Parameters”](#parameters)
### order
[Section titled “order”](#order)
[`Order`](/reference/knotkit/heap/type-aliases/order/)<`A`>
### sources
[Section titled “sources”](#sources)
`Iterable`<`AsyncIterable`<`A`, `any`, `any`> | `Iterable`<`A`, `any`, `any`>>
## Returns
[Section titled “Returns”](#returns)
`AsyncGenerator`<`Awaited`<`A`>, `void`, `unknown`>
# knotkit/static-filter
## Classes
[Section titled “Classes”](#classes)
* [StaticFilterInvalidInputError](/reference/knotkit/static-filter/classes/staticfilterinvalidinputerror/)
* [StaticFilterParseError](/reference/knotkit/static-filter/classes/staticfilterparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [StaticFilterOptions](/reference/knotkit/static-filter/interfaces/staticfilteroptions/)
* [StaticFilter](/reference/knotkit/static-filter/interfaces/staticfilter/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [StaticFilterInvalidInputErrorCode](/reference/knotkit/static-filter/type-aliases/staticfilterinvalidinputerrorcode/)
* [StaticFilterParseErrorCode](/reference/knotkit/static-filter/type-aliases/staticfilterparseerrorcode/)
* [StaticFilterErrorCode](/reference/knotkit/static-filter/type-aliases/staticfiltererrorcode/)
* [StaticFilterKind](/reference/knotkit/static-filter/type-aliases/staticfilterkind/)
* [StaticFilterFactory](/reference/knotkit/static-filter/type-aliases/staticfilterfactory/)
## Variables
[Section titled “Variables”](#variables)
* [STATIC_FILTER_INVALID_INPUT_ERROR_CODES](/reference/knotkit/static-filter/variables/static_filter_invalid_input_error_codes/)
* [STATIC_FILTER_PARSE_ERROR_CODES](/reference/knotkit/static-filter/variables/static_filter_parse_error_codes/)
* [STATIC_FILTER_ERROR_CODES](/reference/knotkit/static-filter/variables/static_filter_error_codes/)
* [\_\_STATIC_FILTER_LAYOUTS](/reference/knotkit/static-filter/variables/static_filter_layouts/)
* [STATIC_FILTER_KINDS](/reference/knotkit/static-filter/variables/static_filter_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [binaryFuse16StaticFilter](/reference/knotkit/static-filter/functions/binaryfuse16staticfilter/)
* [binaryFuse8StaticFilter](/reference/knotkit/static-filter/functions/binaryfuse8staticfilter/)
# StaticFilterInvalidInputError
Defined in: [packages/static-filter/src/errors.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L51)
Thrown when a caller passes keys that are not an iterable of `Uint8Array`, a probe that is not a `Uint8Array`, a seed that is not an unsigned 64-bit `bigint`, more keys than one filter addresses, a key set no construction attempt could place, or an object this package did not produce to `serializeStaticFilter`.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`StaticFilterInvalidInputErrorCode`](/reference/knotkit/static-filter/type-aliases/staticfilterinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new StaticFilterInvalidInputError**(`code`, `message`): `StaticFilterInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"MAX_CAPACITY_EXCEEDED"` | `"INVALID_KEY"` | `"INVALID_SEED"` | `"INVALID_KEYS"` | `"CONSTRUCTION_FAILED"` | `"FOREIGN_STATIC_FILTER"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`StaticFilterInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"MAX_CAPACITY_EXCEEDED"` | `"INVALID_KEY"` | `"INVALID_SEED"` | `"INVALID_KEYS"` | `"CONSTRUCTION_FAILED"` | `"FOREIGN_STATIC_FILTER"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/static-filter"`
Defined in: [packages/static-filter/src/errors.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L52)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# StaticFilterParseError
Defined in: [packages/static-filter/src/errors.ts:56](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L56)
Thrown when decoding a `serializeStaticFilter` artifact that is malformed or internally inconsistent.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`StaticFilterParseErrorCode`](/reference/knotkit/static-filter/type-aliases/staticfilterparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new StaticFilterParseError**(`code`, `message`): `StaticFilterParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"CORRUPT_FILTER_PAYLOAD"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`StaticFilterParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"CORRUPT_FILTER_PAYLOAD"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/static-filter"`
Defined in: [packages/static-filter/src/errors.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L57)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# binaryFuse16StaticFilter
> **binaryFuse16StaticFilter**(`keys`, `options?`): [`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
Defined in: [packages/static-filter/src/binary-fuse-16-static-filter.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/binary-fuse-16-static-filter.ts#L16)
Build an immutable `binary-fuse-16` filter from a known set of keys: two bytes per slot, about 18 to 20 bits per key, and a false-positive rate near 2^-16 (0.0015%).
Construction and probing are those of `binaryFuse8StaticFilter` with 16-bit fingerprints. Builds in expected O(n) time after hashing n inputs, with O(d) temporary storage for d distinct hashes.
## Parameters
[Section titled “Parameters”](#parameters)
### keys
[Section titled “keys”](#keys)
`Iterable`<`Uint8Array`<`ArrayBufferLike`>>
### options?
[Section titled “options?”](#options)
[`StaticFilterOptions`](/reference/knotkit/static-filter/interfaces/staticfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_KEYS` when `keys` is not iterable, `INVALID_KEY` when a key is not a `Uint8Array`, `INVALID_SEED` when `seed` is not an unsigned 64-bit `bigint`, `MAX_CAPACITY_EXCEEDED` past 2^30 distinct keys or when the runtime refuses the allocation, and `CONSTRUCTION_FAILED` when 100 attempts all fail to peel, which a set of distinct hashes does not reach in practice.
# binaryFuse8StaticFilter
> **binaryFuse8StaticFilter**(`keys`, `options?`): [`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
Defined in: [packages/static-filter/src/binary-fuse-8-static-filter.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/binary-fuse-8-static-filter.ts#L17)
Build an immutable `binary-fuse-8` filter from a known set of keys: one byte per slot, about 9 to 10 bits per key, and a false-positive rate near 2^-8 (0.39%).
Every key is hashed with XXH64 under `seed`, repeated hashes are dropped, and the rest are placed by peeling a 3-wise Binary Fuse hypergraph (Graf and Lemire, 2022). A probe reads three slots in three adjacent segments. Builds in expected O(n) time after hashing n inputs, with O(d) temporary storage for d distinct hashes.
## Parameters
[Section titled “Parameters”](#parameters)
### keys
[Section titled “keys”](#keys)
`Iterable`<`Uint8Array`<`ArrayBufferLike`>>
### options?
[Section titled “options?”](#options)
[`StaticFilterOptions`](/reference/knotkit/static-filter/interfaces/staticfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_KEYS` when `keys` is not iterable, `INVALID_KEY` when a key is not a `Uint8Array`, `INVALID_SEED` when `seed` is not an unsigned 64-bit `bigint`, `MAX_CAPACITY_EXCEEDED` past 2^30 distinct keys or when the runtime refuses the allocation, and `CONSTRUCTION_FAILED` when 100 attempts all fail to peel, which a set of distinct hashes does not reach in practice.
# StaticFilter
Defined in: [packages/static-filter/src/static-filter.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L30)
An immutable approximate membership filter over a set of `Uint8Array` keys fixed at construction.
Every key the filter was built from answers `true`: there are no false negatives. A key it was not built from answers `true` with probability about `falsePositiveRateEstimate`. The filter holds fingerprints only, never the keys, so it cannot list, count, or delete them; a changed key set builds a new filter.
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"binary-fuse-8"` | `"binary-fuse-16"`
Defined in: [packages/static-filter/src/static-filter.ts:31](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L31)
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/static-filter/src/static-filter.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L33)
Number of distinct keys the filter was built from. Repeated keys count once.
***
### byteLength
[Section titled “byteLength”](#bytelength)
> `readonly` **byteLength**: `number`
Defined in: [packages/static-filter/src/static-filter.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L35)
Bytes of the fingerprint array: one per slot for `binary-fuse-8`, two for `binary-fuse-16`, 0 when empty.
***
### fingerprintBits
[Section titled “fingerprintBits”](#fingerprintbits)
> `readonly` **fingerprintBits**: `8` | `16`
Defined in: [packages/static-filter/src/static-filter.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L37)
Bits in one fingerprint.
***
### falsePositiveRateEstimate
[Section titled “falsePositiveRateEstimate”](#falsepositiverateestimate)
> `readonly` **falsePositiveRateEstimate**: `number`
Defined in: [packages/static-filter/src/static-filter.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L39)
The theoretical false-positive rate, `2^-fingerprintBits`, or `0` for an empty filter.
***
### mightContain
[Section titled “mightContain”](#mightcontain)
> `readonly` **mightContain**: (`key`) => `boolean`
Defined in: [packages/static-filter/src/static-filter.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L46)
Whether `key` may be one of the keys the filter was built from: always `true` for those keys, and `true` with probability about `falsePositiveRateEstimate` for any other key. Three array reads after one XXH64 hash.
#### Parameters
[Section titled “Parameters”](#parameters)
##### key
[Section titled “key”](#key)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_KEY` when `key` is not a `Uint8Array`.
# StaticFilterOptions
Defined in: [packages/static-filter/src/static-filter.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L15)
Options for [StaticFilterFactory](/reference/knotkit/static-filter/type-aliases/staticfilterfactory/).
## Properties
[Section titled “Properties”](#properties)
### seed?
[Section titled “seed?”](#seed)
> `readonly` `optional` **seed?**: `bigint`
Defined in: [packages/static-filter/src/static-filter.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L20)
Seed for the XXH64 hash of every key and for the first construction attempt, an unsigned 64-bit `bigint`; `0n` when omitted. The same keys and seed build byte-identical filters in every runtime.
# StaticFilterErrorCode
> **StaticFilterErrorCode** = [`StaticFilterInvalidInputErrorCode`](/reference/knotkit/static-filter/type-aliases/staticfilterinvalidinputerrorcode/) | [`StaticFilterParseErrorCode`](/reference/knotkit/static-filter/type-aliases/staticfilterparseerrorcode/)
Defined in: [packages/static-filter/src/errors.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L39)
A machine-readable error code emitted by `knotkit/static-filter`.
# StaticFilterFactory
> **StaticFilterFactory** = (`keys`, `options?`) => [`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
Defined in: [packages/static-filter/src/static-filter.ts:50](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L50)
A factory that builds a [StaticFilter](/reference/knotkit/static-filter/interfaces/staticfilter/) once from a known set of keys.
## Parameters
[Section titled “Parameters”](#parameters)
### keys
[Section titled “keys”](#keys)
`Iterable`<`Uint8Array`>
### options?
[Section titled “options?”](#options)
[`StaticFilterOptions`](/reference/knotkit/static-filter/interfaces/staticfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
[`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
# StaticFilterInvalidInputErrorCode
> **StaticFilterInvalidInputErrorCode** = *typeof* [`STATIC_FILTER_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/static-filter/variables/static_filter_invalid_input_error_codes/)\[`number`]
Defined in: [packages/static-filter/src/errors.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L33)
A machine-readable invalid-input code emitted by `knotkit/static-filter`.
# StaticFilterKind
> **StaticFilterKind** = *typeof* [`STATIC_FILTER_KINDS`](/reference/knotkit/static-filter/variables/static_filter_kinds/)\[`number`]
Defined in: [packages/static-filter/src/static-filter.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L12)
A layout of [StaticFilter](/reference/knotkit/static-filter/interfaces/staticfilter/), the serializable discriminant its `kind` reports.
# StaticFilterParseErrorCode
> **StaticFilterParseErrorCode** = *typeof* [`STATIC_FILTER_PARSE_ERROR_CODES`](/reference/knotkit/static-filter/variables/static_filter_parse_error_codes/)\[`number`]
Defined in: [packages/static-filter/src/errors.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L36)
A machine-readable parse code emitted by `knotkit/static-filter`.
# STATIC_FILTER_ERROR_CODES
> `const` **STATIC_FILTER_ERROR_CODES**: readonly [`StaticFilterErrorCode`](/reference/knotkit/static-filter/type-aliases/staticfiltererrorcode/)\[]
Defined in: [packages/static-filter/src/errors.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L42)
Every code emitted by `knotkit/static-filter`, in stable category order.
# STATIC_FILTER_INVALID_INPUT_ERROR_CODES
> `const` **STATIC_FILTER_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_KEYS"`, `"INVALID_KEY"`, `"INVALID_SEED"`, `"CONSTRUCTION_FAILED"`, `"MAX_CAPACITY_EXCEEDED"`, `"FOREIGN_STATIC_FILTER"`]
Defined in: [packages/static-filter/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L4)
The canonical, ordered list of machine-readable input errors emitted by `knotkit/static-filter`.
# STATIC_FILTER_KINDS
> `const` **STATIC_FILTER_KINDS**: readonly \[`"binary-fuse-8"`, `"binary-fuse-16"`]
Defined in: [packages/static-filter/src/static-filter.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/static-filter.ts#L6)
The filter layouts this package constructs, in recommendation order. Both are 3-wise Binary Fuse filters (Graf and Lemire, 2022) and differ only in fingerprint width: `binary-fuse-8` stores one byte per slot for a false-positive rate near 2^-8, and `binary-fuse-16` stores two for a rate near 2^-16.
# __STATIC_FILTER_LAYOUTS
> `const` **\_\_STATIC_FILTER_LAYOUTS**: `Readonly`<`Record`<[`StaticFilterKind`](/reference/knotkit/static-filter/type-aliases/staticfilterkind/), [`StaticFilterFactory`](/reference/knotkit/static-filter/type-aliases/staticfilterfactory/)>>
Defined in: [packages/static-filter/src/layouts.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/layouts.ts#L11)
Every filter layout this package constructs, keyed by the `kind` it reports.
Exported so a property test, a benchmark, or a `problems/*` preset can sweep every layout without naming one. A caller building one filter imports `binaryFuse8StaticFilter` or `binaryFuse16StaticFilter` directly.
# STATIC_FILTER_PARSE_ERROR_CODES
> `const` **STATIC_FILTER_PARSE_ERROR_CODES**: readonly \[`"INVALID_PACKAGE_HEADER"`, `"UNKNOWN_KIND"`, `"CORRUPT_FILTER_PAYLOAD"`, `"INVALID_MAGIC"`, `"UNSUPPORTED_ENVELOPE_VERSION"`, `"UNSUPPORTED_PAYLOAD_VERSION"`, `"INVALID_SECTION_GEOMETRY"`, `"NONZERO_PADDING"`, `"MISALIGNED_SECTION"`, `"TRUNCATED_PAYLOAD"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`]
Defined in: [packages/static-filter/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/errors.ts#L14)
Codes carried specifically by [StaticFilterParseError](/reference/knotkit/static-filter/classes/staticfilterparseerror/).
# knotkit/static-filter/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeStaticFilterOptions](/reference/knotkit/static-filter/wire/interfaces/serializestaticfilteroptions/)
## Functions
[Section titled “Functions”](#functions)
* [serializeStaticFilter](/reference/knotkit/static-filter/wire/functions/serializestaticfilter/)
* [deserializeStaticFilter](/reference/knotkit/static-filter/wire/functions/deserializestaticfilter/)
# deserializeStaticFilter
> **deserializeStaticFilter**(`bytes`): [`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
Defined in: [packages/static-filter/src/serialization.ts:212](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/serialization.ts#L212)
Decode bytes written by [serializeStaticFilter](/reference/knotkit/static-filter/wire/functions/serializestaticfilter/).
The payload is validated before a filter is returned, in O(byte length): a parameters section of exactly 28 bytes, a key count of at most 2^30, a segment length that is a power of two in `[4, 2^18]`, a segment count length that is a positive multiple of it, at least one slot per key, a fingerprint section of exactly one or two bytes per slot, an attempt seed that one of the first 100 construction attempts under the seed draws, and, for an empty filter, no slots at all. Fingerprint values cannot be checked without the keys; pass `{ integrity: true }` when serializing to catch accidental corruption. The filter owns a copy of the bytes.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
[`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
## Throws
[Section titled “Throws”](#throws)
With `CORRUPT_FILTER_PAYLOAD` when the payload breaks one of those rules, `INVALID_PACKAGE_HEADER` for a malformed header, `UNKNOWN_KIND` for a kind tag this release does not read, or a shared wire code from `STATIC_FILTER_PARSE_ERROR_CODES` for a malformed envelope.
# serializeStaticFilter
> **serializeStaticFilter**(`filter`, `options?`): `Uint8Array`
Defined in: [packages/static-filter/src/serialization.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/serialization.ts#L93)
Serialize a filter into binary bytes that restore the same answers for every key.
Writes the XXH64 seed, the attempt seed that peeled, the key count, the segment geometry, and the fingerprint array inside a `knotkit/wire` envelope with a producer version. Runs in O(byteLength). Two filters built from the same key set and seed serialize to identical bytes, whatever order or repetition the keys arrived in.
## Parameters
[Section titled “Parameters”](#parameters)
### filter
[Section titled “filter”](#filter)
[`StaticFilter`](/reference/knotkit/static-filter/interfaces/staticfilter/)
### options?
[Section titled “options?”](#options)
[`SerializeStaticFilterOptions`](/reference/knotkit/static-filter/wire/interfaces/serializestaticfilteroptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `FOREIGN_STATIC_FILTER` when `filter` was not produced by this package, or `MAX_CAPACITY_EXCEEDED` when the runtime cannot allocate the artifact.
# SerializeStaticFilterOptions
Defined in: [packages/static-filter/src/serialization.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/serialization.ts#L63)
Optional behavior for binary filter serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/static-filter/src/serialization.ts:65](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/static-filter/src/serialization.ts#L65)
Include a CRC-32 integrity section for accidental corruption detection.
# knotkit/term-index
## Classes
[Section titled “Classes”](#classes)
* [TermIndexInvalidInputError](/reference/knotkit/term-index/classes/termindexinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [TermPosting](/reference/knotkit/term-index/interfaces/termposting/)
* [TermHit](/reference/knotkit/term-index/interfaces/termhit/)
* [TermSearchOptions](/reference/knotkit/term-index/interfaces/termsearchoptions/)
* [TermIndex](/reference/knotkit/term-index/interfaces/termindex/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [TermIndexInvalidInputErrorCode](/reference/knotkit/term-index/type-aliases/termindexinvalidinputerrorcode/)
* [TermIndexErrorCode](/reference/knotkit/term-index/type-aliases/termindexerrorcode/)
## Variables
[Section titled “Variables”](#variables)
* [TERM_INDEX_INVALID_INPUT_ERROR_CODES](/reference/knotkit/term-index/variables/term_index_invalid_input_error_codes/)
* [TERM_INDEX_ERROR_CODES](/reference/knotkit/term-index/variables/term_index_error_codes/)
## Functions
[Section titled “Functions”](#functions)
* [termIndex](/reference/knotkit/term-index/functions/termindex/)
# TermIndexInvalidInputError
Defined in: [packages/term-index/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L18)
A token list or limit is invalid, or the corpus exceeds the index’s capacity.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`TermIndexInvalidInputErrorCode`](/reference/knotkit/term-index/type-aliases/termindexinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new TermIndexInvalidInputError**(`code`, `message`): `TermIndexInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"MAX_CAPACITY_EXCEEDED"` | `"INVALID_LIMIT"` | `"INVALID_TERMS"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`TermIndexInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"MAX_CAPACITY_EXCEEDED"` | `"INVALID_LIMIT"` | `"INVALID_TERMS"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/term-index"`
Defined in: [packages/term-index/src/errors.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L19)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# termIndex
> **termIndex**<`R`>(`records`, `termsOf`): [`TermIndex`](/reference/knotkit/term-index/interfaces/termindex/)
Defined in: [packages/term-index/src/term-index.ts:205](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L205)
Build a read-only counted index from caller-tokenized documents. The selector runs once per input record. The index retains terms, counts, and document positions. It can discard the source records after construction.
Expected O(n + t) build time for n documents and t token occurrences, plus the selector’s work. Build workspace and retained storage are O(n + v + p) for v vocabulary terms and p distinct postings.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### R
[Section titled “R”](#r)
`R`
## Parameters
[Section titled “Parameters”](#parameters)
### records
[Section titled “records”](#records)
`Iterable`<`R`>
### termsOf
[Section titled “termsOf”](#termsof)
(`record`, `id`) => readonly `string`\[]
## Returns
[Section titled “Returns”](#returns)
[`TermIndex`](/reference/knotkit/term-index/interfaces/termindex/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_TERMS` for a selector result other than an array of strings or `MAX_CAPACITY_EXCEEDED` when corpus counts or packed storage exceed their bounds. Errors thrown by the input iterable and selector propagate.
# TermHit
Defined in: [packages/term-index/src/term-index.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L11)
One document’s summed BM25 score over the distinct matching query terms.
## Properties
[Section titled “Properties”](#properties)
### id
[Section titled “id”](#id)
> `readonly` **id**: `number`
Defined in: [packages/term-index/src/term-index.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L12)
***
### score
[Section titled “score”](#score)
> `readonly` **score**: `number`
Defined in: [packages/term-index/src/term-index.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L13)
# TermIndex
Defined in: [packages/term-index/src/term-index.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L24)
A read-only counted inverted index. Document IDs are zero-based input positions.
## Properties
[Section titled “Properties”](#properties)
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/term-index/src/term-index.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L26)
Number of distinct terms.
***
### documentCount
[Section titled “documentCount”](#documentcount)
> `readonly` **documentCount**: `number`
Defined in: [packages/term-index/src/term-index.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L28)
Number of documents, including those with no terms.
***
### tokenCount
[Section titled “tokenCount”](#tokencount)
> `readonly` **tokenCount**: `number`
Defined in: [packages/term-index/src/term-index.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L30)
Total token occurrences, including repeats.
***
### averageDocumentLength
[Section titled “averageDocumentLength”](#averagedocumentlength)
> `readonly` **averageDocumentLength**: `number`
Defined in: [packages/term-index/src/term-index.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L32)
Tokens per document, or zero if there are no documents.
***
### keys
[Section titled “keys”](#keys)
> `readonly` **keys**: () => `IterableIterator`<`string`>
Defined in: [packages/term-index/src/term-index.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L34)
Iterate distinct terms in first-seen order.
#### Returns
[Section titled “Returns”](#returns)
`IterableIterator`<`string`>
***
### documentLength
[Section titled “documentLength”](#documentlength)
> `readonly` **documentLength**: (`id`) => `number` | `undefined`
Defined in: [packages/term-index/src/term-index.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L36)
Number of tokens in a document. Returns undefined for an absent ID. O(1).
#### Parameters
[Section titled “Parameters”](#parameters)
##### id
[Section titled “id”](#id)
`number`
#### Returns
[Section titled “Returns”](#returns-1)
`number` | `undefined`
***
### documentFrequency
[Section titled “documentFrequency”](#documentfrequency)
> `readonly` **documentFrequency**: (`term`) => `number`
Defined in: [packages/term-index/src/term-index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L38)
Number of documents containing the term. Returns zero for an absent term. Expected O(1).
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### term
[Section titled “term”](#term)
`string`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
***
### postings
[Section titled “postings”](#postings)
> `readonly` **postings**: (`term`) => `IterableIterator`<[`TermPosting`](/reference/knotkit/term-index/interfaces/termposting/)>
Defined in: [packages/term-index/src/term-index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L40)
Iterate the term’s counted postings in ascending document ID order.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### term
[Section titled “term”](#term-1)
`string`
#### Returns
[Section titled “Returns”](#returns-3)
`IterableIterator`<[`TermPosting`](/reference/knotkit/term-index/interfaces/termposting/)>
***
### search
[Section titled “search”](#search)
> `readonly` **search**: (`terms`, `options?`) => readonly [`TermHit`](/reference/knotkit/term-index/interfaces/termhit/)\[]
Defined in: [packages/term-index/src/term-index.ts:47](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L47)
Rank documents matching any supplied exact term. Ties in score favor lower IDs. Repeated query terms contribute once. The returned array and hits are independent of the index.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### terms
[Section titled “terms”](#terms)
readonly `string`\[]
##### options?
[Section titled “options?”](#options)
[`TermSearchOptions`](/reference/knotkit/term-index/interfaces/termsearchoptions/)
#### Returns
[Section titled “Returns”](#returns-4)
readonly [`TermHit`](/reference/knotkit/term-index/interfaces/termhit/)\[]
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_LIMIT` for a limit outside the nonnegative safe integers or `INVALID_TERMS` for an argument other than an array of strings. Eligibility accessor errors propagate.
# TermPosting
Defined in: [packages/term-index/src/term-index.ts:5](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L5)
One exact term’s occurrence count in a document.
## Properties
[Section titled “Properties”](#properties)
### id
[Section titled “id”](#id)
> `readonly` **id**: `number`
Defined in: [packages/term-index/src/term-index.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L6)
***
### count
[Section titled “count”](#count)
> `readonly` **count**: `number`
Defined in: [packages/term-index/src/term-index.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L7)
# TermSearchOptions
Defined in: [packages/term-index/src/term-index.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L16)
## Properties
[Section titled “Properties”](#properties)
### limit?
[Section titled “limit?”](#limit)
> `readonly` `optional` **limit?**: `number`
Defined in: [packages/term-index/src/term-index.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L18)
Maximum number of hits. Defaults to 10. Zero yields no hits.
***
### eligibleIds?
[Section titled “eligibleIds?”](#eligibleids)
> `readonly` `optional` **eligibleIds?**: `Pick`<`ReadonlySet`<`number`>, `"has"`>
Defined in: [packages/term-index/src/term-index.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/term-index.ts#L20)
Restricts hits before ranking. Corpus statistics still include every indexed document.
# TermIndexErrorCode
> **TermIndexErrorCode** = *typeof* [`TERM_INDEX_ERROR_CODES`](/reference/knotkit/term-index/variables/term_index_error_codes/)\[`number`]
Defined in: [packages/term-index/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L15)
# TermIndexInvalidInputErrorCode
> **TermIndexInvalidInputErrorCode** = *typeof* `invalidInputCodes`\[`number`]
Defined in: [packages/term-index/src/errors.ts:8](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L8)
# TERM_INDEX_ERROR_CODES
> `const` **TERM_INDEX_ERROR_CODES**: readonly [`TermIndexInvalidInputErrorCode`](/reference/knotkit/term-index/type-aliases/termindexinvalidinputerrorcode/)\[]
Defined in: [packages/term-index/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L11)
All error codes emitted by `knotkit/term-index`.
# TERM_INDEX_INVALID_INPUT_ERROR_CODES
> `const` **TERM_INDEX_INVALID_INPUT_ERROR_CODES**: `Readonly`<*typeof* `invalidInputCodes`>
Defined in: [packages/term-index/src/errors.ts:6](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/term-index/src/errors.ts#L6)
Codes for invalid search limits, token lists, and packed storage capacity.
# knotkit/trie
## Classes
[Section titled “Classes”](#classes)
* [TrieInvalidInputError](/reference/knotkit/trie/classes/trieinvalidinputerror/)
* [TrieParseError](/reference/knotkit/trie/classes/trieparseerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SegmentedTrieEntry](/reference/knotkit/trie/interfaces/segmentedtrieentry/)
* [SegmentedTrie](/reference/knotkit/trie/interfaces/segmentedtrie/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [TrieInvalidInputErrorCode](/reference/knotkit/trie/type-aliases/trieinvalidinputerrorcode/)
* [TrieParseErrorCode](/reference/knotkit/trie/type-aliases/trieparseerrorcode/)
* [TrieErrorCode](/reference/knotkit/trie/type-aliases/trieerrorcode/)
* [SegmentedKey](/reference/knotkit/trie/type-aliases/segmentedkey/)
* [SegmentedTrieKind](/reference/knotkit/trie/type-aliases/segmentedtriekind/)
* [SegmentedTrieFactory](/reference/knotkit/trie/type-aliases/segmentedtriefactory/)
## Variables
[Section titled “Variables”](#variables)
* [TRIE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/trie/variables/trie_invalid_input_error_codes/)
* [TRIE_PARSE_ERROR_CODES](/reference/knotkit/trie/variables/trie_parse_error_codes/)
* [TRIE_ERROR_CODES](/reference/knotkit/trie/variables/trie_error_codes/)
* [\_\_SEGMENTED_TRIE_LAYOUTS](/reference/knotkit/trie/variables/segmented_trie_layouts/)
* [SEGMENTED_TRIE_KINDS](/reference/knotkit/trie/variables/segmented_trie_kinds/)
## Functions
[Section titled “Functions”](#functions)
* [compressedSegmentedTrie](/reference/knotkit/trie/functions/compressedsegmentedtrie/)
* [uncompressedSegmentedTrie](/reference/knotkit/trie/functions/uncompressedsegmentedtrie/)
# TrieInvalidInputError
Defined in: [packages/trie/src/errors.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L53)
Thrown when a caller passes a key that violates a `SegmentedTrie`’s public contract.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`TrieInvalidInputErrorCode`](/reference/knotkit/trie/type-aliases/trieinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new TrieInvalidInputError**(`code`, `message`): `TrieInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"` | `"FOREIGN_STRUCTURE"` | `"INVALID_KEY"` | `"INVALID_SEGMENT"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`TrieInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"` | `"SERIALIZATION_LIMIT_EXCEEDED"` | `"MISSING_ELEMENT_CODEC"` | `"FOREIGN_STRUCTURE"` | `"INVALID_KEY"` | `"INVALID_SEGMENT"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/trie"`
Defined in: [packages/trie/src/errors.ts:54](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L54)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# TrieParseError
Defined in: [packages/trie/src/errors.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L58)
Thrown when decoding a `SerializedSegmentedTrie` that is malformed or fails validation.
## Extends
[Section titled “Extends”](#extends)
* [`ParseError`](/reference/knotkit/errors/classes/parseerror/)<[`TrieParseErrorCode`](/reference/knotkit/trie/type-aliases/trieparseerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new TrieParseError**(`code`, `message`): `TrieParseError`
Defined in: [packages/errors/src/index.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L57)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"MISSING_ENTRIES"` | `"INVALID_ENTRY"` | `"DUPLICATE_KEY"` | `"INVALID_SEGMENT"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`TrieParseError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`constructor`](/reference/knotkit/errors/classes/parseerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"ParseError"`
Defined in: [packages/errors/src/index.ts:55](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L55)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`_tag`](/reference/knotkit/errors/classes/parseerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_CODEC_RESULT"` | `"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"` | `"UNKNOWN_KIND"` | `"INVALID_PACKAGE_HEADER"` | `"INVALID_VALUE"` | `"INVALID_SHAPE"` | `"UNSUPPORTED_SCHEMA_VERSION"` | `"MISSING_ENTRIES"` | `"INVALID_ENTRY"` | `"DUPLICATE_KEY"` | `"INVALID_SEGMENT"`
Defined in: [packages/errors/src/index.ts:58](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L58)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`code`](/reference/knotkit/errors/classes/parseerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/trie"`
Defined in: [packages/trie/src/errors.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L59)
#### Overrides
[Section titled “Overrides”](#overrides)
[`ParseError`](/reference/knotkit/errors/classes/parseerror/).[`moduleName`](/reference/knotkit/errors/classes/parseerror/#modulename)
# compressedSegmentedTrie
> **compressedSegmentedTrie**<`V`>(`entries?`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/compressed-segmented-trie.ts:186](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/compressed-segmented-trie.ts#L186)
Create a [SegmentedTrie](/reference/knotkit/trie/interfaces/segmentedtrie/) that packs runs of non-branching segments into edge labels: the path compression a radix tree applies to characters, applied here to whole segments.
A node exists only where keys branch or end. Keys always end at nodes: an insert whose key runs out inside an edge splits the edge around a fresh node. `delete` prunes nodes it empties and folds a resulting single-child chain back into its parent’s edge, so the layout holds one node per branch point or key end of the live keys, whatever the operation history.
The observable contract matches [uncompressedSegmentedTrie](/reference/knotkit/trie/functions/uncompressedsegmentedtrie/) exactly. The trade is in the constants: fewer nodes, and one `Map` lookup per edge instead of one per segment during a walk, against edge comparisons on every operation and split bookkeeping on insert. Prefer it when keys are deep or mostly non-branching, the shapes that also make its smaller node count matter.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### entries?
[Section titled “entries?”](#entries)
`Iterable`<[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>, `any`, `any`>
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.
## Returns
[Section titled “Returns”](#returns)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
## Throws
[Section titled “Throws”](#throws)
When an entry key is not an array of strings.
# uncompressedSegmentedTrie
> **uncompressedSegmentedTrie**<`V`>(`entries?`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:267](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L267)
Create a [SegmentedTrie](/reference/knotkit/trie/interfaces/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](/reference/knotkit/trie/functions/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` keyed on the joined string when only exact matches are needed.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### entries?
[Section titled “entries?”](#entries)
`Iterable`<[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>, `any`, `any`>
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.
## Returns
[Section titled “Returns”](#returns)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
## Throws
[Section titled “Throws”](#throws)
When an entry key is not an array of strings.
# SegmentedTrie
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:74](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L74)
A prefix tree keyed on segment sequences rather than characters, mapping each stored key to a value and resolving queries by longest prefix.
Keys and queries are arrays of strings, the tokens a caller gets from splitting a delimiter-separated string such as a slug or a dotted path. Segments compare by exact string equality, so `'Google'` and `'google'` are different tokens and the empty string is a legal one, as produced by splitting on consecutive delimiters. The empty key `[]` is legal too and makes `longestPrefix` answer every query, which suits default entries.
The structure is built once from a known key set and queried many times, which is the workload `longestPrefix` exists for: one O(m) walk replaces the O(m²) scan that repeatedly slices and rejoins ever-shorter prefixes to test them against a `Set`.
All operations mutate in place and run in O(m) expected time for a key or query of `m` segments. Lookups allocate only the arrays they return. How keys share structure along a common prefix is each layout’s choice, which its factory documents.
Mutating methods validate their key and throw on a non-array key or a non-string segment. Reading methods treat such input as a miss instead, because an invalid query cannot corrupt anything. Neither check costs more than the walk itself.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"uncompressed"` | `"compressed"`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:76](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L76)
Stable identifier for the implementation’s storage layout.
***
### size
[Section titled “size”](#size)
> `readonly` **size**: `number`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L78)
Number of stored keys. O(1).
***
### has
[Section titled “has”](#has)
> **has**: (`segments`) => `boolean`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:80](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L80)
Return `true` when the exact key is stored. O(m) expected.
#### Parameters
[Section titled “Parameters”](#parameters)
##### segments
[Section titled “segments”](#segments)
[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
#### Returns
[Section titled “Returns”](#returns)
`boolean`
***
### get
[Section titled “get”](#get)
> **get**: (`segments`) => `V` | `undefined`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:85](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L85)
Return the value stored under the exact key, or `undefined` when it is not stored. O(m) expected.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### segments
[Section titled “segments”](#segments-1)
[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
#### Returns
[Section titled “Returns”](#returns-1)
`V` | `undefined`
***
### set
[Section titled “set”](#set)
> **set**: (`segments`, `value`) => `void`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:93](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L93)
Store `value` under the key, overwriting any value already there without changing `size`. O(m) expected.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### segments
[Section titled “segments”](#segments-2)
[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
##### value
[Section titled “value”](#value)
`V`
#### Returns
[Section titled “Returns”](#returns-2)
`void`
#### Throws
[Section titled “Throws”](#throws)
When the key is not an array of strings. Nothing is stored in that case, not even a partial path.
***
### delete
[Section titled “delete”](#delete)
> **delete**: (`segments`) => `boolean`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:102](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L102)
Remove the key and its value. Empty branches are pruned, while prefixes of the removed key stay stored. O(m) expected.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### segments
[Section titled “segments”](#segments-3)
[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
#### Returns
[Section titled “Returns”](#returns-3)
`boolean`
`true` when a stored key was removed.
#### Throws
[Section titled “Throws”](#throws-1)
When the key is not an array of strings.
***
### longestPrefix
[Section titled “longestPrefix”](#longestprefix)
> **longestPrefix**: (`segments`) => [`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`> | `undefined`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:112](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L112)
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.
#### Parameters
[Section titled “Parameters”](#parameters-4)
##### segments
[Section titled “segments”](#segments-4)
[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
#### Returns
[Section titled “Returns”](#returns-4)
[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`> | `undefined`
***
### keys
[Section titled “keys”](#keys)
> **keys**: () => `IterableIterator`<[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)>
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:122](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L122)
Iterate over every stored key, depth-first with each node’s children in insertion order, so a key precedes its extensions. O(k) total for k stored segments, plus O(n) for the n keys collected.
The keys present when the call was made are collected before the first step, so mutating the trie while iterating neither extends nor disturbs the walk. Each yielded array is fresh and safe to keep.
#### Returns
[Section titled “Returns”](#returns-5)
`IterableIterator`<[`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)>
***
### entries
[Section titled “entries”](#entries)
> **entries**: () => `IterableIterator`<[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>>
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:127](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L127)
Iterate over every stored entry in the order [keys](/reference/knotkit/trie/interfaces/segmentedtrie/#keys) documents, each with its value. Same complexity and snapshot guarantees as [keys](/reference/knotkit/trie/interfaces/segmentedtrie/#keys).
#### Returns
[Section titled “Returns”](#returns-6)
`IterableIterator`<[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>>
# SegmentedTrieEntry
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L41)
One key-value pair stored in a segmented trie. A plain, inert record with no behavior.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### segments
[Section titled “segments”](#segments)
> `readonly` **segments**: [`SegmentedKey`](/reference/knotkit/trie/type-aliases/segmentedkey/)
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L43)
The stored key: one segment per trie level.
***
### value
[Section titled “value”](#value)
> `readonly` **value**: `V`
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L45)
The value stored under [segments](/reference/knotkit/trie/interfaces/segmentedtrieentry/#segments).
# SegmentedKey
> **SegmentedKey** = readonly `string`\[]
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L38)
A segmented-trie key: an ordered sequence of string tokens, one per trie level.
Splitting a delimiter-separated string into segments is the caller’s decision, which keeps the delimiter and any normalization such as lowercasing out of the structure. It also keeps keys unambiguous: joining back with a delimiter cannot tell `['a_b', 'c']` from `['a', 'b_c']`, while the segment arrays stay distinct.
# SegmentedTrieFactory
> **SegmentedTrieFactory** = <`V`>(`entries?`) => [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:156](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L156)
Create a [SegmentedTrie](/reference/knotkit/trie/interfaces/segmentedtrie/) from an optional iterable of entries, pre-populated in iteration order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### entries?
[Section titled “entries?”](#entries)
`Iterable`<[`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>>
## Returns
[Section titled “Returns”](#returns)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
# SegmentedTrieKind
> **SegmentedTrieKind** = *typeof* [`SEGMENTED_TRIE_KINDS`](/reference/knotkit/trie/variables/segmented_trie_kinds/)\[`number`]
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:141](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L141)
Storage layouts provided by this package.
# TrieErrorCode
> **TrieErrorCode** = [`TrieInvalidInputErrorCode`](/reference/knotkit/trie/type-aliases/trieinvalidinputerrorcode/) | [`TrieParseErrorCode`](/reference/knotkit/trie/type-aliases/trieparseerrorcode/)
Defined in: [packages/trie/src/errors.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L45)
A machine-readable error code emitted by `knotkit/trie`.
# TrieInvalidInputErrorCode
> **TrieInvalidInputErrorCode** = *typeof* [`TRIE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/trie/variables/trie_invalid_input_error_codes/)\[`number`]
Defined in: [packages/trie/src/errors.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L39)
# TrieParseErrorCode
> **TrieParseErrorCode** = *typeof* [`TRIE_PARSE_ERROR_CODES`](/reference/knotkit/trie/variables/trie_parse_error_codes/)\[`number`]
Defined in: [packages/trie/src/errors.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L42)
A machine-readable parse code emitted by `knotkit/trie`.
# SEGMENTED_TRIE_KINDS
> `const` **SEGMENTED_TRIE_KINDS**: readonly \[`"uncompressed"`, `"compressed"`]
Defined in: [packages/trie/src/uncompressed-segmented-trie.ts:138](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/uncompressed-segmented-trie.ts#L138)
Every storage layout this package provides, as a runtime value.
Exported so a caller can enumerate the layouts exhaustively without restating them, and so [SegmentedTrieKind](/reference/knotkit/trie/type-aliases/segmentedtriekind/) is derived from the list rather than duplicating it. `__SEGMENTED_TRIE_LAYOUTS` in `layouts.ts` is the matching construction table.
# __SEGMENTED_TRIE_LAYOUTS
> `const` **\_\_SEGMENTED_TRIE_LAYOUTS**: `SegmentedTrieLayouts`
Defined in: [packages/trie/src/layouts.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/layouts.ts#L24)
Every layout, in `SEGMENTED_TRIE_KINDS` order. Frozen, so no caller can swap one for another.
# TRIE_ERROR_CODES
> `const` **TRIE_ERROR_CODES**: readonly [`TrieErrorCode`](/reference/knotkit/trie/type-aliases/trieerrorcode/)\[]
Defined in: [packages/trie/src/errors.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L48)
Every code emitted by `knotkit/trie`, in stable category order.
# TRIE_INVALID_INPUT_ERROR_CODES
> `const` **TRIE_INVALID_INPUT_ERROR_CODES**: readonly \[`"INVALID_KEY"`, `"INVALID_SEGMENT"`, `"FOREIGN_STRUCTURE"`, `"MISSING_ELEMENT_CODEC"`, `"INVALID_CODEC_RESULT"`, `"NON_INJECTIVE_CODEC"`, `"SERIALIZATION_LIMIT_EXCEEDED"`]
Defined in: [packages/trie/src/errors.ts:4](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L4)
Codes carried specifically by [TrieInvalidInputError](/reference/knotkit/trie/classes/trieinvalidinputerror/).
# TRIE_PARSE_ERROR_CODES
> `const` **TRIE_PARSE_ERROR_CODES**: readonly \[`"INVALID_SEGMENT"`, `"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"`, `"INVALID_CODEC_RESULT"`, `"DECODE_BUDGET_EXCEEDED"`, `"UNSTABLE_BUFFER"`, `"WRONG_FORMAT"`, `"INTEGRITY_MISMATCH"`, `"INVALID_PACKAGE_HEADER"`]
Defined in: [packages/trie/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/errors.ts#L15)
Codes carried specifically by [TrieParseError](/reference/knotkit/trie/classes/trieparseerror/).
# knotkit/trie/wire
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [SerializeSegmentedTrieOptions](/reference/knotkit/trie/wire/interfaces/serializesegmentedtrieoptions/)
* [DeserializeSegmentedTrieOptions](/reference/knotkit/trie/wire/interfaces/deserializesegmentedtrieoptions/)
* [SerializedSegmentedTrie](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/)
* [DeserializeSegmentedTrieJsonOptions](/reference/knotkit/trie/wire/interfaces/deserializesegmentedtriejsonoptions/)
## Variables
[Section titled “Variables”](#variables)
* [TRIE_MAX_DECODE_NODES](/reference/knotkit/trie/wire/variables/trie_max_decode_nodes/)
* [TRIE_MAX_DECODE_STRING_TABLE_BYTES](/reference/knotkit/trie/wire/variables/trie_max_decode_string_table_bytes/)
* [TRIE_MAX_DECODE_KEY_SEGMENTS](/reference/knotkit/trie/wire/variables/trie_max_decode_key_segments/)
## Functions
[Section titled “Functions”](#functions)
* [serializeSegmentedTrie](/reference/knotkit/trie/wire/functions/serializesegmentedtrie/)
* [deserializeSegmentedTrie](/reference/knotkit/trie/wire/functions/deserializesegmentedtrie/)
* [serializeSegmentedTrieJson](/reference/knotkit/trie/wire/functions/serializesegmentedtriejson/)
* [deserializeSegmentedTrieJson](/reference/knotkit/trie/wire/functions/deserializesegmentedtriejson/)
# deserializeSegmentedTrie
> **deserializeSegmentedTrie**<`V`>(`value`, `options`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/serialization/binary.ts:164](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L164)
Restore a binary segmented trie after validating its complete node graph, resolved keys, codec results, and decode budgets in staging data.
A factory override preserves exact entry order across layouts because node rows and terminal values are emitted in depth-first iteration order.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value)
`unknown`
### options
[Section titled “options”](#options)
[`DeserializeSegmentedTrieOptions`](/reference/knotkit/trie/wire/interfaces/deserializesegmentedtrieoptions/)<`V`>
## Returns
[Section titled “Returns”](#returns)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC` when `options.codec` is absent, which is a caller-contract violation rather than a decode failure.
## Throws
[Section titled “Throws”](#throws-1)
For malformed bytes, unsupported versions, noncanonical node or string tables, invalid values, or decode-budget violations.
# deserializeSegmentedTrieJson
## Call Signature
[Section titled “Call Signature”](#call-signature)
> **deserializeSegmentedTrieJson**<`V`>(`serialized`, `create?`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/serialization/json.ts:201](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L201)
Rebuild a segmented trie from a [SerializedSegmentedTrie](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/), restoring its recorded implementation unless a factory override is supplied. O(k) time for k stored segments.
Entries are replayed in serialized order, so a round trip through `serializeSegmentedTrieJson` and `deserializeSegmentedTrieJson` preserves `size`, iteration order, every stored value, and every `longestPrefix` answer.
Untyped input produces a `SegmentedTrie`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters)
#### V
[Section titled “V”](#v)
`V`
### Parameters
[Section titled “Parameters”](#parameters)
#### serialized
[Section titled “serialized”](#serialized)
[`SerializedSegmentedTrie`](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/)<`V`>
The trie to restore, either statically typed or decoded as `unknown`.
#### create?
[Section titled “create?”](#create)
[`SegmentedTrieFactory`](/reference/knotkit/trie/type-aliases/segmentedtriefactory/)
### Returns
[Section titled “Returns”](#returns)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
### Throws
[Section titled “Throws”](#throws)
When the serialized shape, a segment, or a decoded value is invalid, or an entry repeats a key. Distinguish causes with `error.code`, one of TrieParseErrorCode.
## Call Signature
[Section titled “Call Signature”](#call-signature-1)
> **deserializeSegmentedTrieJson**<`V`>(`serialized`, `options`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
Defined in: [packages/trie/src/serialization/json.ts:205](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L205)
Rebuild a segmented trie from a [SerializedSegmentedTrie](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/), restoring its recorded implementation unless a factory override is supplied. O(k) time for k stored segments.
Entries are replayed in serialized order, so a round trip through `serializeSegmentedTrieJson` and `deserializeSegmentedTrieJson` preserves `size`, iteration order, every stored value, and every `longestPrefix` answer.
Untyped input produces a `SegmentedTrie`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Type Parameters
[Section titled “Type Parameters”](#type-parameters-1)
#### V
[Section titled “V”](#v-1)
`V`
### Parameters
[Section titled “Parameters”](#parameters-1)
#### serialized
[Section titled “serialized”](#serialized-1)
`unknown`
The trie to restore, either statically typed or decoded as `unknown`.
#### options
[Section titled “options”](#options)
[`DeserializeSegmentedTrieJsonOptions`](/reference/knotkit/trie/wire/interfaces/deserializesegmentedtriejsonoptions/)<`V`>
### Returns
[Section titled “Returns”](#returns-1)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
### Throws
[Section titled “Throws”](#throws-1)
When the serialized shape, a segment, or a decoded value is invalid, or an entry repeats a key. Distinguish causes with `error.code`, one of TrieParseErrorCode.
## Call Signature
[Section titled “Call Signature”](#call-signature-2)
> **deserializeSegmentedTrieJson**(`serialized`): [`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`unknown`>
Defined in: [packages/trie/src/serialization/json.ts:209](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L209)
Rebuild a segmented trie from a [SerializedSegmentedTrie](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/), restoring its recorded implementation unless a factory override is supplied. O(k) time for k stored segments.
Entries are replayed in serialized order, so a round trip through `serializeSegmentedTrieJson` and `deserializeSegmentedTrieJson` preserves `size`, iteration order, every stored value, and every `longestPrefix` answer.
Untyped input produces a `SegmentedTrie`. Pass a value type guard to validate decoded values and recover a narrower value type.
### Parameters
[Section titled “Parameters”](#parameters-2)
#### serialized
[Section titled “serialized”](#serialized-2)
`unknown`
The trie to restore, either statically typed or decoded as `unknown`.
### Returns
[Section titled “Returns”](#returns-2)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`unknown`>
### Throws
[Section titled “Throws”](#throws-2)
When the serialized shape, a segment, or a decoded value is invalid, or an entry repeats a key. Distinguish causes with `error.code`, one of TrieParseErrorCode.
# serializeSegmentedTrie
> **serializeSegmentedTrie**<`V`>(`trie`, `codec`, `options?`): `Uint8Array`
Defined in: [packages/trie/src/serialization/binary.ts:106](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L106)
Serialize a segmented trie as a shared UTF-8 string table, a depth-first parent-pointer node table, and a parallel terminal-value run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### trie
[Section titled “trie”](#trie)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`V`>
### options?
[Section titled “options?”](#options)
[`SerializeSegmentedTrieOptions`](/reference/knotkit/trie/wire/interfaces/serializesegmentedtrieoptions/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `MISSING_ELEMENT_CODEC` when `codec` is absent, and with `INVALID_SEGMENT`, `INVALID_CODEC_RESULT`, `NON_INJECTIVE_CODEC`, or `SERIALIZATION_LIMIT_EXCEEDED` when the trie cannot be represented safely.
# serializeSegmentedTrieJson
> **serializeSegmentedTrieJson**<`V`>(`trie`): [`SerializedSegmentedTrie`](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/)<`V`>
Defined in: [packages/trie/src/serialization/json.ts:52](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L52)
Capture the kind and every entry of a segmented trie as a [SerializedSegmentedTrie](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/). O(k) time and space for k stored segments.
The value is a snapshot: later mutations of the source structure cannot change it. Two tries that hold the same entries in the same iteration order serialize identically, regardless of the operation history that built them, because the tree shape and the pruning it experienced are not observable.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Parameters
[Section titled “Parameters”](#parameters)
### trie
[Section titled “trie”](#trie)
[`SegmentedTrie`](/reference/knotkit/trie/interfaces/segmentedtrie/)<`V`>
## Returns
[Section titled “Returns”](#returns)
[`SerializedSegmentedTrie`](/reference/knotkit/trie/wire/interfaces/serializedsegmentedtrie/)<`V`>
# DeserializeSegmentedTrieJsonOptions
Defined in: [packages/trie/src/serialization/json.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L36)
Runtime decoding options for data whose value type is not yet known.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### isValue
[Section titled “isValue”](#isvalue)
> `readonly` **isValue**: (`value`) => `value is V`
Defined in: [packages/trie/src/serialization/json.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L38)
Prove the type of every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is V`
***
### create?
[Section titled “create?”](#create)
> `readonly` `optional` **create?**: [`SegmentedTrieFactory`](/reference/knotkit/trie/type-aliases/segmentedtriefactory/)
Defined in: [packages/trie/src/serialization/json.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L40)
Optional implementation override.
# DeserializeSegmentedTrieOptions
Defined in: [packages/trie/src/serialization/binary.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L57)
Runtime inputs needed to decode a segmented trie’s generic value run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### codec
[Section titled “codec”](#codec)
> `readonly` **codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`V`>
Defined in: [packages/trie/src/serialization/binary.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L59)
Codec matching the one used to serialize stored values.
***
### isValue?
[Section titled “isValue?”](#isvalue)
> `readonly` `optional` **isValue?**: (`value`) => `value is V`
Defined in: [packages/trie/src/serialization/binary.ts:61](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L61)
Optional validation applied to every decoded value.
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns)
`value is V`
***
### create?
[Section titled “create?”](#create)
> `readonly` `optional` **create?**: [`SegmentedTrieFactory`](/reference/knotkit/trie/type-aliases/segmentedtriefactory/)
Defined in: [packages/trie/src/serialization/binary.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L63)
Restore into a layout other than the artifact’s recorded kind.
# SerializedSegmentedTrie
Defined in: [packages/trie/src/serialization/json.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L26)
A plain, inert description of a segmented trie: the implementation kind and every entry, in the iteration order `entries()` reports. It holds no behavior and no reference to the structure it came from, so it can be stored, compared, structurally cloned, or sent through `postMessage`. It survives `JSON.stringify` when the values themselves do.
`kind` identifies the storage layout to restore. Restoring replays the entries in order, so a round trip also preserves iteration order: replayed children land in each node’s `Map` exactly as the walk first found them.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### V
[Section titled “V”](#v)
`V`
## Properties
[Section titled “Properties”](#properties)
### schemaVersion
[Section titled “schemaVersion”](#schemaversion)
> `readonly` **schemaVersion**: `1`
Defined in: [packages/trie/src/serialization/json.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L28)
Wire-schema version.
***
### kind
[Section titled “kind”](#kind)
> `readonly` **kind**: `"uncompressed"` | `"compressed"`
Defined in: [packages/trie/src/serialization/json.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L30)
The storage layout to restore when no factory override is supplied.
***
### entries
[Section titled “entries”](#entries)
> `readonly` **entries**: readonly [`SegmentedTrieEntry`](/reference/knotkit/trie/interfaces/segmentedtrieentry/)<`V`>\[]
Defined in: [packages/trie/src/serialization/json.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/json.ts#L32)
Every entry, in iteration order.
# SerializeSegmentedTrieOptions
Defined in: [packages/trie/src/serialization/binary.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L51)
Optional behavior for binary segmented-trie serialization.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/trie/src/serialization/binary.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L53)
Include a CRC-32 integrity section for accidental corruption detection.
# TRIE_MAX_DECODE_KEY_SEGMENTS
> `const` **TRIE_MAX_DECODE_KEY_SEGMENTS**: `4000000` = `4_000_000`
Defined in: [packages/trie/src/serialization/binary.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L48)
Maximum total resolved key segments staged by a trie decoder.
# TRIE_MAX_DECODE_NODES
> `const` **TRIE_MAX_DECODE_NODES**: `1000000` = `1_000_000`
Defined in: [packages/trie/src/serialization/binary.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L42)
Maximum number of root and segment nodes staged by a trie decoder.
# TRIE_MAX_DECODE_STRING_TABLE_BYTES
> `const` **TRIE_MAX_DECODE_STRING_TABLE_BYTES**: `number`
Defined in: [packages/trie/src/serialization/binary.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/trie/src/serialization/binary.ts#L45)
Maximum encoded string-table bytes accepted by a trie decoder.
# knotkit/wire
## Classes
[Section titled “Classes”](#classes)
* [WireInvalidInputError](/reference/knotkit/wire/classes/wireinvalidinputerror/)
## Interfaces
[Section titled “Interfaces”](#interfaces)
* [ArtifactFormatDefinition](/reference/knotkit/wire/interfaces/artifactformatdefinition/)
* [ArtifactPayload](/reference/knotkit/wire/interfaces/artifactpayload/)
* [ArtifactSerializeOptions](/reference/knotkit/wire/interfaces/artifactserializeoptions/)
* [ArtifactFormat](/reference/knotkit/wire/interfaces/artifactformat/)
* [ElementCodec](/reference/knotkit/wire/interfaces/elementcodec/)
* [InjectiveElementOptions](/reference/knotkit/wire/interfaces/injectiveelementoptions/)
* [WireSection](/reference/knotkit/wire/interfaces/wiresection/)
* [WireEnvelopeInput](/reference/knotkit/wire/interfaces/wireenvelopeinput/)
* [WireEnvelope](/reference/knotkit/wire/interfaces/wireenvelope/)
* [WireEnvelopeDecodeOptions](/reference/knotkit/wire/interfaces/wireenvelopedecodeoptions/)
* [StateBridge](/reference/knotkit/wire/interfaces/statebridge/)
## Type Aliases
[Section titled “Type Aliases”](#type-aliases)
* [WireEnvelopeParts](/reference/knotkit/wire/type-aliases/wireenvelopeparts/)
* [WireTamperReason](/reference/knotkit/wire/type-aliases/wiretamperreason/)
* [WireInvalidInputErrorCode](/reference/knotkit/wire/type-aliases/wireinvalidinputerrorcode/)
* [WireErrorCode](/reference/knotkit/wire/type-aliases/wireerrorcode/)
* [WireFailureReason](/reference/knotkit/wire/type-aliases/wirefailurereason/)
* [WireFailureCode](/reference/knotkit/wire/type-aliases/wirefailurecode/)
* [WireFailureFactories](/reference/knotkit/wire/type-aliases/wirefailurefactories/)
* [IntegerWidth](/reference/knotkit/wire/type-aliases/integerwidth/)
* [WireSerializationCodeMap](/reference/knotkit/wire/type-aliases/wireserializationcodemap/)
## Variables
[Section titled “Variables”](#variables)
* [uint32Codec](/reference/knotkit/wire/variables/uint32codec/)
* [uint64Codec](/reference/knotkit/wire/variables/uint64codec/)
* [float64Codec](/reference/knotkit/wire/variables/float64codec/)
* [stringCodec](/reference/knotkit/wire/variables/stringcodec/)
* [WIRE_TAMPER_REASONS](/reference/knotkit/wire/variables/wire_tamper_reasons/)
* [WIRE_INVALID_INPUT_ERROR_CODES](/reference/knotkit/wire/variables/wire_invalid_input_error_codes/)
* [WIRE_ERROR_CODES](/reference/knotkit/wire/variables/wire_error_codes/)
* [WIRE_FAILURE_REASONS](/reference/knotkit/wire/variables/wire_failure_reasons/)
* [WIRE_FAILURE_CODES](/reference/knotkit/wire/variables/wire_failure_codes/)
* [KNOTKIT_PACKAGE_VERSION](/reference/knotkit/wire/variables/knotkit_package_version/)
## Functions
[Section titled “Functions”](#functions)
* [artifactFormat](/reference/knotkit/wire/functions/artifactformat/)
* [isElementCodec](/reference/knotkit/wire/functions/iselementcodec/)
* [encodeElements](/reference/knotkit/wire/functions/encodeelements/)
* [encodeInjectiveElements](/reference/knotkit/wire/functions/encodeinjectiveelements/)
* [decodeElements](/reference/knotkit/wire/functions/decodeelements/)
* [serializeEnvelope](/reference/knotkit/wire/functions/serializeenvelope/)
* [deserializeEnvelope](/reference/knotkit/wire/functions/deserializeenvelope/)
* [inspectEnvelope](/reference/knotkit/wire/functions/inspectenvelope/)
* [tamperEnvelope](/reference/knotkit/wire/functions/tamperenvelope/)
* [crc32](/reference/knotkit/wire/functions/crc32/)
* [failWire](/reference/knotkit/wire/functions/failwire/)
* [assertStableBuffer](/reference/knotkit/wire/functions/assertstablebuffer/)
* [assertDecodeBudget](/reference/knotkit/wire/functions/assertdecodebudget/)
* [requireSection](/reference/knotkit/wire/functions/requiresection/)
* [wireFailureFactories](/reference/knotkit/wire/functions/wirefailurefactories/)
* [rejectSection](/reference/knotkit/wire/functions/rejectsection/)
* [chooseIntegerWidth](/reference/knotkit/wire/functions/chooseintegerwidth/)
* [integerWidthMaximum](/reference/knotkit/wire/functions/integerwidthmaximum/)
* [writeUnsigned](/reference/knotkit/wire/functions/writeunsigned/)
* [readUnsigned](/reference/knotkit/wire/functions/readunsigned/)
* [writeIntegerRun](/reference/knotkit/wire/functions/writeintegerrun/)
* [readIntegerRun](/reference/knotkit/wire/functions/readintegerrun/)
* [encodeDeltas](/reference/knotkit/wire/functions/encodedeltas/)
* [decodeDeltas](/reference/knotkit/wire/functions/decodedeltas/)
* [readUint32ViewOrCopy](/reference/knotkit/wire/functions/readuint32vieworcopy/)
* [writeSemver](/reference/knotkit/wire/functions/writesemver/)
* [readSemver](/reference/knotkit/wire/functions/readsemver/)
* [mapWireSerializationError](/reference/knotkit/wire/functions/mapwireserializationerror/)
* [stateBridge](/reference/knotkit/wire/functions/statebridge/)
* [encodeStringTable](/reference/knotkit/wire/functions/encodestringtable/)
* [decodeStringTable](/reference/knotkit/wire/functions/decodestringtable/)
# WireInvalidInputError
Defined in: [packages/wire/src/errors.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L21)
Thrown when a caller passes an invalid `knotkit/wire` argument.
## Extends
[Section titled “Extends”](#extends)
* [`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/)<[`WireInvalidInputErrorCode`](/reference/knotkit/wire/type-aliases/wireinvalidinputerrorcode/)>
## Constructors
[Section titled “Constructors”](#constructors)
### Constructor
[Section titled “Constructor”](#constructor)
> **new WireInvalidInputError**(`code`, `message`): `WireInvalidInputError`
Defined in: [packages/errors/src/index.ts:40](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L40)
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
`"INVALID_ARGUMENT"` | `"INVALID_STRING"` | `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"`
##### message
[Section titled “message”](#message)
`string`
#### Returns
[Section titled “Returns”](#returns)
`WireInvalidInputError`
#### Inherited from
[Section titled “Inherited from”](#inherited-from)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`constructor`](/reference/knotkit/errors/classes/invalidinputerror/#constructor)
## Properties
[Section titled “Properties”](#properties)
### \_tag
[Section titled “\_tag”](#_tag)
> `readonly` **\_tag**: `"InvalidInputError"`
Defined in: [packages/errors/src/index.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L38)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-1)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`_tag`](/reference/knotkit/errors/classes/invalidinputerror/#_tag)
***
### code
[Section titled “code”](#code-1)
> `readonly` **code**: `"INVALID_ARGUMENT"` | `"INVALID_STRING"` | `"INVALID_CODEC_RESULT"` | `"NON_INJECTIVE_CODEC"`
Defined in: [packages/errors/src/index.ts:41](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/errors/src/index.ts#L41)
#### Inherited from
[Section titled “Inherited from”](#inherited-from-2)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`code`](/reference/knotkit/errors/classes/invalidinputerror/#code-1)
***
### moduleName
[Section titled “moduleName”](#modulename)
> `readonly` **moduleName**: `"knotkit/wire"`
Defined in: [packages/wire/src/errors.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L22)
#### Overrides
[Section titled “Overrides”](#overrides)
[`InvalidInputError`](/reference/knotkit/errors/classes/invalidinputerror/).[`moduleName`](/reference/knotkit/errors/classes/invalidinputerror/#modulename)
# artifactFormat
> **artifactFormat**<`Kind`, `Failure`, `InvalidInputCode`>(`definition`): [`ArtifactFormat`](/reference/knotkit/wire/interfaces/artifactformat/)<`Kind`, `Failure`>
Defined in: [packages/wire/src/artifact-format.ts:84](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L84)
Declare a module’s binary artifact format.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* `string`
### Failure
[Section titled “Failure”](#failure)
`Failure` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
### InvalidInputCode
[Section titled “InvalidInputCode”](#invalidinputcode)
`InvalidInputCode` *extends* `string`
## Parameters
[Section titled “Parameters”](#parameters)
### definition
[Section titled “definition”](#definition)
[`ArtifactFormatDefinition`](/reference/knotkit/wire/interfaces/artifactformatdefinition/)<`Kind`, `Failure`, `InvalidInputCode`>
## Returns
[Section titled “Returns”](#returns)
[`ArtifactFormat`](/reference/knotkit/wire/interfaces/artifactformat/)<`Kind`, `Failure`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when the magic is not four bytes, the payload version or a tag is not a byte, or two kinds share a tag.
# assertDecodeBudget
> **assertDecodeBudget**<`E`>(`count`, `maximum`, `factories`): `void`
Defined in: [packages/wire/src/guards.ts:48](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L48)
Enforce a caller-declared decode-work budget before allocating output.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### count
[Section titled “count”](#count)
`number`
### maximum
[Section titled “maximum”](#maximum)
`number`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
## Returns
[Section titled “Returns”](#returns)
`void`
## Throws
[Section titled “Throws”](#throws)
The package-owned `decode-budget-exceeded` error.
# assertStableBuffer
> **assertStableBuffer**<`E`>(`bytes`, `factories`): `void`
Defined in: [packages/wire/src/guards.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L32)
Reject buffers whose byte length could change while being decoded.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
## Returns
[Section titled “Returns”](#returns)
`void`
## Throws
[Section titled “Throws”](#throws)
The package-owned `unstable-buffer` error.
# chooseIntegerWidth
> **chooseIntegerWidth**(`maximum`): [`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
Defined in: [packages/wire/src/primitives.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L19)
Choose the smallest fixed width that can represent `maximum`.
## Parameters
[Section titled “Parameters”](#parameters)
### maximum
[Section titled “maximum”](#maximum)
`number`
## Returns
[Section titled “Returns”](#returns)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `maximum` is not a non-negative safe integer.
# crc32
> **crc32**(`bytes`): `number`
Defined in: [packages/wire/src/envelope.ts:390](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L390)
Compute the standard reflected CRC-32 used by integrity sections.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
`number`
# decodeDeltas
> **decodeDeltas**(`deltas`, `offset?`, `count?`): `number`\[]
Defined in: [packages/wire/src/primitives.ts:195](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L195)
Reconstruct prefix sums from all or one bounded range of a non-negative delta run.
## Parameters
[Section titled “Parameters”](#parameters)
### deltas
[Section titled “deltas”](#deltas)
readonly `number`\[]
### offset?
[Section titled “offset?”](#offset)
`number` = `0`
### count?
[Section titled “count?”](#count)
`number` = `...`
## Returns
[Section titled “Returns”](#returns)
`number`\[]
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when the range or a delta is invalid.
# decodeElements
> **decodeElements**<`Value`, `E`>(`bytes`, `count`, `codec`, `factories`, `isValue?`): `Value`\[]
Defined in: [packages/wire/src/element-codec.ts:151](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L151)
Decode a bounded run into staging values before a structure is materialized.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### count
[Section titled “count”](#count)
`number`
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`Value`>
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### isValue?
[Section titled “isValue?”](#isvalue)
(`value`) => `value is Value`
## Returns
[Section titled “Returns”](#returns)
`Value`\[]
## Throws
[Section titled “Throws”](#throws)
The package-owned parse error selected by `factories` when the codec result is invalid.
# decodeStringTable
> **decodeStringTable**<`E`>(`input`, `factories`, `expectedCount?`): `string`\[]
Defined in: [packages/wire/src/string-table.ts:81](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/string-table.ts#L81)
Validate and decode a UTF-8 string table.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### input
[Section titled “input”](#input)
`Uint8Array`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### expectedCount?
[Section titled “expectedCount?”](#expectedcount)
`number`
## Returns
[Section titled “Returns”](#returns)
`string`\[]
## Throws
[Section titled “Throws”](#throws)
The package-owned parse error selected by `factories` for invalid input.
# deserializeEnvelope
> **deserializeEnvelope**<`E`>(`bytes`, `magic`, `factories`, `options?`): [`WireEnvelope`](/reference/knotkit/wire/interfaces/wireenvelope/)
Defined in: [packages/wire/src/envelope.ts:142](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L142)
Validate and decode an envelope before a structure allocates mutable state. Unknown section tags are validated but need not be copied into the result.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### magic
[Section titled “magic”](#magic)
`Uint8Array`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### options?
[Section titled “options?”](#options)
[`WireEnvelopeDecodeOptions`](/reference/knotkit/wire/interfaces/wireenvelopedecodeoptions/)
## Returns
[Section titled “Returns”](#returns)
[`WireEnvelope`](/reference/knotkit/wire/interfaces/wireenvelope/)
## Throws
[Section titled “Throws”](#throws)
The package-owned parse error selected by `factories` for invalid input.
# encodeDeltas
> **encodeDeltas**(`values`): `number`\[]
Defined in: [packages/wire/src/primitives.ts:171](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L171)
Convert an ascending run to first-value-plus-deltas form.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `number`\[]
## Returns
[Section titled “Returns”](#returns)
`number`\[]
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when input is not ascending non-negative safe integers.
# encodeElements
> **encodeElements**<`Value`>(`values`, `codec`): `Uint8Array`
Defined in: [packages/wire/src/element-codec.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L32)
Encode values as one contiguous codec run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `Value`\[]
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`Value`>
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when a codec throws or returns invalid bytes.
## Throws
[Section titled “Throws”](#throws-1)
A package error thrown directly by a caller-supplied codec.
# encodeInjectiveElements
> **encodeInjectiveElements**<`Value`>(`values`, `codec`, `options?`): `Uint8Array`
Defined in: [packages/wire/src/element-codec.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L59)
Encode values as one contiguous codec run, proving the codec injective over them.
Two positions may share an encoding only when `equals` reports them equal, so a structure whose round trip depends on distinct bytes per stored value fails before an artifact is emitted rather than after it is restored.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `Value`\[]
### codec
[Section titled “codec”](#codec)
[`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`Value`>
### options?
[Section titled “options?”](#options)
[`InjectiveElementOptions`](/reference/knotkit/wire/interfaces/injectiveelementoptions/)<`Value`>
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_CODEC_RESULT` when a codec throws or returns a non-`Uint8Array`, `NON_INJECTIVE_CODEC` when it emits no bytes or repeats bytes across distinct values, and `INVALID_ARGUMENT` when the run exceeds a representable length.
## Throws
[Section titled “Throws”](#throws-1)
A package error thrown directly by a caller-supplied codec.
# encodeStringTable
> **encodeStringTable**(`strings`): `Uint8Array`
Defined in: [packages/wire/src/string-table.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/string-table.ts#L16)
Encode strings as flags, byte offsets, and one contiguous UTF-8 blob.
## Parameters
[Section titled “Parameters”](#parameters)
### strings
[Section titled “strings”](#strings)
readonly `string`\[]
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_STRING` when a string contains an unpaired surrogate, or `INVALID_ARGUMENT` when the encoded table exceeds a representable limit.
# failWire
> **failWire**<`E`>(`factories`, `reason`, `detail`): `never`
Defined in: [packages/wire/src/guards.ts:19](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L19)
Throw the package error selected for a shared wire-validation reason.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### reason
[Section titled “reason”](#reason)
`"invalid-magic"` | `"unsupported-envelope-version"` | `"unsupported-payload-version"` | `"invalid-section-geometry"` | `"nonzero-padding"` | `"misaligned-section"` | `"truncated-payload"` | `"invalid-codec-result"` | `"decode-budget-exceeded"` | `"unstable-buffer"` | `"wrong-format"` | `"integrity-mismatch"` | `"unknown-kind"`
### detail
[Section titled “detail”](#detail)
`string`
## Returns
[Section titled “Returns”](#returns)
`never`
## Throws
[Section titled “Throws”](#throws)
The package-owned error selected by `reason`.
# inspectEnvelope
> **inspectEnvelope**(`bytes`): [`WireEnvelopeParts`](/reference/knotkit/wire/type-aliases/wireenvelopeparts/)
Defined in: [packages/wire/src/envelope.ts:286](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L286)
Take a valid envelope apart into owned copies of every part, whichever module wrote it.
The inverse of [serializeEnvelope](/reference/knotkit/wire/functions/serializeenvelope/) for bytes already known to be an artifact: framing the parts again reproduces the input, and framing them with one part changed yields a valid envelope around the change. It expects no magic and maps no failure to a module’s parse error, so it is not a decoder for untrusted bytes; that is [deserializeEnvelope](/reference/knotkit/wire/functions/deserializeenvelope/).
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
## Returns
[Section titled “Returns”](#returns)
[`WireEnvelopeParts`](/reference/knotkit/wire/type-aliases/wireenvelopeparts/)
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `bytes` is not a valid envelope.
# integerWidthMaximum
> **integerWidthMaximum**(`width`): `number`
Defined in: [packages/wire/src/primitives.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L30)
The largest value a field of `width` bytes stores: the unsigned maximum for 1, 2, and 4; the safe-integer maximum for 8.
## Parameters
[Section titled “Parameters”](#parameters)
### width
[Section titled “width”](#width)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
## Returns
[Section titled “Returns”](#returns)
`number`
# isElementCodec
> **isElementCodec**<`Value`>(`value`): `value is ElementCodec`
Defined in: [packages/wire/src/element-codec.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L17)
Whether a runtime value has the callable shape of an element codec.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
## Parameters
[Section titled “Parameters”](#parameters)
### value
[Section titled “value”](#value-1)
`unknown`
## Returns
[Section titled “Returns”](#returns)
`value is ElementCodec`
# mapWireSerializationError
> **mapWireSerializationError**<`Code`, `T`>(`codes`, `makeError`, `detail`, `write`): `T`
Defined in: [packages/wire/src/serialization-errors.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/serialization-errors.ts#L37)
Run one write, translating every `knotkit/wire` caller-contract failure into the package’s own error and code.
Wire rejects a caller contract for four reasons a structure package must restate in its own closed list: an argument out of range (`INVALID_ARGUMENT`), an unpaired surrogate with no strict UTF-8 encoding (`INVALID_STRING`), a codec returning malformed bytes (`INVALID_CODEC_RESULT`), and a codec mapping two distinct values to identical bytes (`NON_INJECTIVE_CODEC`). Without this mapping, a caller catching the package’s `InvalidInputError` would see a bare `WireInvalidInputError` escape instead, which breaks the package’s promise that every throw carries a code from its own list.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Code
[Section titled “Code”](#code)
`Code` *extends* `string`
### T
[Section titled “T”](#t)
`T`
## Parameters
[Section titled “Parameters”](#parameters)
### codes
[Section titled “codes”](#codes)
[`WireSerializationCodeMap`](/reference/knotkit/wire/type-aliases/wireserializationcodemap/)<`Code`>
The package’s translation of each wire code.
### makeError
[Section titled “makeError”](#makeerror)
(`code`, `detail`) => [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
Builds the package’s error from a translated code.
### detail
[Section titled “detail”](#detail)
`string`
The operation named in the message, such as `heap artifact`.
### write
[Section titled “write”](#write)
() => `T`
The write to run.
## Returns
[Section titled “Returns”](#returns)
`T`
## Throws
[Section titled “Throws”](#throws)
The package error selected by `codes` for a wire caller-contract failure; any other error is rethrown untouched.
# readIntegerRun
> **readIntegerRun**<`E`>(`bytes`, `width`, `count`, `factories`): `number`\[]
Defined in: [packages/wire/src/primitives.ts:111](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L111)
Validate a declared count against section length, then decode its run.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### width
[Section titled “width”](#width)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
### count
[Section titled “count”](#count)
`number`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
## Returns
[Section titled “Returns”](#returns)
`number`\[]
## Throws
[Section titled “Throws”](#throws)
The package-owned geometry error selected by `factories`.
# readSemver
> **readSemver**(`view`, `offset`): `string`
Defined in: [packages/wire/src/primitives.ts:293](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L293)
Read the three little-endian unsigned 16-bit fields written by [writeSemver](/reference/knotkit/wire/functions/writesemver/).
## Parameters
[Section titled “Parameters”](#parameters)
### view
[Section titled “view”](#view)
`DataView`
### offset
[Section titled “offset”](#offset)
`number`
## Returns
[Section titled “Returns”](#returns)
`string`
# readUint32ViewOrCopy
> **readUint32ViewOrCopy**(`bytes`, `offset`, `count`): `Uint32Array`
Defined in: [packages/wire/src/primitives.ts:233](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L233)
Read a native little-endian uint32 view when compatible, or an equal copied run otherwise.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### offset
[Section titled “offset”](#offset)
`number`
### count
[Section titled “count”](#count)
`number`
## Returns
[Section titled “Returns”](#returns)
`Uint32Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when the requested run exceeds `bytes`.
# readUnsigned
> **readUnsigned**(`view`, `offset`, `width`): `number`
Defined in: [packages/wire/src/primitives.ts:57](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L57)
Read one unsigned little-endian field of `width` bytes at `offset`.
A width-8 field is returned as a `number` and may exceed the safe-integer range; callers that need the safe bound use [readIntegerRun](/reference/knotkit/wire/functions/readintegerrun/), which rejects it with the package’s geometry failure.
## Parameters
[Section titled “Parameters”](#parameters)
### view
[Section titled “view”](#view)
`DataView`
### offset
[Section titled “offset”](#offset)
`number`
### width
[Section titled “width”](#width)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
## Returns
[Section titled “Returns”](#returns)
`number`
# rejectSection
> **rejectSection**<`E`>(`sections`, `tag`, `factories`, `detail`): `void`
Defined in: [packages/wire/src/guards.ts:112](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L112)
Reject an artifact carrying a section its layout forbids.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### sections
[Section titled “sections”](#sections)
readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
### tag
[Section titled “tag”](#tag)
`number`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### detail
[Section titled “detail”](#detail)
`string`
## Returns
[Section titled “Returns”](#returns)
`void`
## Throws
[Section titled “Throws”](#throws)
The package-owned `invalid-section-geometry` error.
# requireSection
> **requireSection**<`E`>(`sections`, `tag`, `factories`, `detail`): `Uint8Array`
Defined in: [packages/wire/src/guards.ts:63](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L63)
Return the only section carrying `tag`, or fail with package-owned geometry.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### sections
[Section titled “sections”](#sections)
readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
### tag
[Section titled “tag”](#tag)
`number`
### factories
[Section titled “factories”](#factories)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
### detail
[Section titled “detail”](#detail)
`string`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
The package-owned `invalid-section-geometry` error.
# serializeEnvelope
> **serializeEnvelope**(`input`): `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L59)
Serialize package bytes into a little-endian, aligned, sectioned envelope.
## Parameters
[Section titled “Parameters”](#parameters)
### input
[Section titled “input”](#input)
[`WireEnvelopeInput`](/reference/knotkit/wire/interfaces/wireenvelopeinput/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when header values, section tags, or artifact size are invalid.
# stateBridge
> **stateBridge**<`State`>(`key`): [`StateBridge`](/reference/knotkit/wire/interfaces/statebridge/)<`State`>
Defined in: [packages/wire/src/state-bridge.ts:59](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/state-bridge.ts#L59)
Create the [StateBridge](/reference/knotkit/wire/interfaces/statebridge/) for one package, keyed by the string in its `Symbol.for` key.
A package owns exactly one bridge. Its key is part of no wire format: it identifies the attached state within a realm, and nothing persists it.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### State
[Section titled “State”](#state)
`State`
## Parameters
[Section titled “Parameters”](#parameters)
### key
[Section titled “key”](#key)
`string`
A `knotkit//@` key. The version suffix allows a later release to move its state shape without reading state attached by an older copy loaded beside it.
## Returns
[Section titled “Returns”](#returns)
[`StateBridge`](/reference/knotkit/wire/interfaces/statebridge/)<`State`>
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `key` does not match that shape.
# tamperEnvelope
> **tamperEnvelope**(`bytes`, `reason`): `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:324](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L324)
Copy a valid artifact and damage the copy so that decoding it fails for exactly `reason`.
Every reason but `unsupported-payload-version` is raised by [deserializeEnvelope](/reference/knotkit/wire/functions/deserializeenvelope/); that one yields a valid envelope carrying another payload version, for the owning package’s gate to refuse.
## Parameters
[Section titled “Parameters”](#parameters)
### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
### reason
[Section titled “reason”](#reason)
`"invalid-magic"` | `"unsupported-envelope-version"` | `"unsupported-payload-version"` | `"invalid-section-geometry"` | `"nonzero-padding"` | `"misaligned-section"` | `"truncated-payload"` | `"unstable-buffer"` | `"integrity-mismatch"`
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `bytes` is not a valid envelope, when it has no section for `invalid-section-geometry` or `misaligned-section` to damage, or when `unstable-buffer` is asked of a runtime that exposes no `SharedArrayBuffer`.
# wireFailureFactories
> **wireFailureFactories**<`E`>(`create`): [`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
Defined in: [packages/wire/src/guards.ts:97](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L97)
Build one package parse-error factory per wire failure reason.
`create` receives the code a consumer package owns for each reason, so the package error constructor type-checks that its closed code list covers every member of [WIRE_FAILURE_REASONS](/reference/knotkit/wire/variables/wire_failure_reasons/).
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Parameters
[Section titled “Parameters”](#parameters)
### create
[Section titled “create”](#create)
(`code`, `detail`) => `E`
## Returns
[Section titled “Returns”](#returns)
[`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`E`>
# writeIntegerRun
> **writeIntegerRun**(`values`, `width`): `Uint8Array`
Defined in: [packages/wire/src/primitives.ts:78](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L78)
Encode unsigned integers at one declared little-endian width.
## Parameters
[Section titled “Parameters”](#parameters)
### values
[Section titled “values”](#values)
readonly `number`\[]
### width
[Section titled “width”](#width)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
## Returns
[Section titled “Returns”](#returns)
`Uint8Array`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when a value does not fit `width`.
# writeSemver
> **writeSemver**(`view`, `offset`, `version`): `void`
Defined in: [packages/wire/src/primitives.ts:270](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L270)
Write a producer version as three little-endian unsigned 16-bit fields.
Occupies six bytes from `offset`.
## Parameters
[Section titled “Parameters”](#parameters)
### view
[Section titled “view”](#view)
`DataView`
### offset
[Section titled “offset”](#offset)
`number`
### version
[Section titled “version”](#version)
`string`
## Returns
[Section titled “Returns”](#returns)
`void`
## Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` unless `version` is three non-negative integers, each at most 65,535, separated by dots.
# writeUnsigned
> **writeUnsigned**(`view`, `offset`, `width`, `value`): `void`
Defined in: [packages/wire/src/primitives.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L39)
Write one unsigned little-endian field of `width` bytes at `offset`.
The caller has already bounded `value` to [integerWidthMaximum](/reference/knotkit/wire/functions/integerwidthmaximum/); this primitive does not re-check it.
## Parameters
[Section titled “Parameters”](#parameters)
### view
[Section titled “view”](#view)
`DataView`
### offset
[Section titled “offset”](#offset)
`number`
### width
[Section titled “width”](#width)
[`IntegerWidth`](/reference/knotkit/wire/type-aliases/integerwidth/)
### value
[Section titled “value”](#value)
`number`
## Returns
[Section titled “Returns”](#returns)
`void`
# ArtifactFormat
Defined in: [packages/wire/src/artifact-format.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L51)
One module’s binary artifact: the prelude every decoder runs before it reads its own header, and the framing every encoder applies after it has built its own sections.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* `string`
### Failure
[Section titled “Failure”](#failure)
`Failure` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
## Properties
[Section titled “Properties”](#properties)
### failures
[Section titled “failures”](#failures)
> `readonly` **failures**: [`WireFailureFactories`](/reference/knotkit/wire/type-aliases/wirefailurefactories/)<`Failure`>
Defined in: [packages/wire/src/artifact-format.ts:53](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L53)
The module’s parse-error factory for every wire failure reason, for the wire guards and readers.
***
### serialize
[Section titled “serialize”](#serialize)
> `readonly` **serialize**: (`build`, `options?`) => `Uint8Array`
Defined in: [packages/wire/src/artifact-format.ts:60](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L60)
Run `build` and frame its payload under this format’s magic and payload version.
#### Parameters
[Section titled “Parameters”](#parameters)
##### build
[Section titled “build”](#build)
() => [`ArtifactPayload`](/reference/knotkit/wire/interfaces/artifactpayload/)
##### options?
[Section titled “options?”](#options)
[`ArtifactSerializeOptions`](/reference/knotkit/wire/interfaces/artifactserializeoptions/)
#### Returns
[Section titled “Returns”](#returns)
`Uint8Array`
#### Throws
[Section titled “Throws”](#throws)
The module’s invalid-input error for every wire caller-contract failure raised by `build` or by the framing; any other error is rethrown untouched.
***
### deserialize
[Section titled “deserialize”](#deserialize)
> `readonly` **deserialize**: (`value`) => [`ArtifactPayload`](/reference/knotkit/wire/interfaces/artifactpayload/)
Defined in: [packages/wire/src/artifact-format.ts:67](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L67)
Validate untrusted input as this format’s envelope and return the module-owned bytes.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### value
[Section titled “value”](#value)
`unknown`
#### Returns
[Section titled “Returns”](#returns-1)
[`ArtifactPayload`](/reference/knotkit/wire/interfaces/artifactpayload/)
#### Throws
[Section titled “Throws”](#throws-1)
The module’s parse error: `wrong-format` for a value that is not a `Uint8Array`, an envelope reason for malformed bytes, and `unsupported-payload-version` for another payload version.
***
### kindTag
[Section titled “kindTag”](#kindtag)
> `readonly` **kindTag**: (`kind`) => `number`
Defined in: [packages/wire/src/artifact-format.ts:69](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L69)
The byte `kind` is written as.
#### Parameters
[Section titled “Parameters”](#parameters-2)
##### kind
[Section titled “kind”](#kind-1)
`Kind`
#### Returns
[Section titled “Returns”](#returns-2)
`number`
***
### kindOf
[Section titled “kindOf”](#kindof)
> `readonly` **kindOf**: (`tag`) => `Kind`
Defined in: [packages/wire/src/artifact-format.ts:75](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L75)
The kind a header’s tag byte names.
#### Parameters
[Section titled “Parameters”](#parameters-3)
##### tag
[Section titled “tag”](#tag)
`number`
#### Returns
[Section titled “Returns”](#returns-3)
`Kind`
#### Throws
[Section titled “Throws”](#throws-2)
The module’s `unknown-kind` parse error for a tag no kind is written as.
# ArtifactFormatDefinition
Defined in: [packages/wire/src/artifact-format.ts:10](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L10)
What one module declares, once, about the binary artifact it writes and reads.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Kind
[Section titled “Kind”](#kind)
`Kind` *extends* `string`
### Failure
[Section titled “Failure”](#failure)
`Failure` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
### InvalidInputCode
[Section titled “InvalidInputCode”](#invalidinputcode)
`InvalidInputCode` *extends* `string`
## Properties
[Section titled “Properties”](#properties)
### name
[Section titled “name”](#name)
> `readonly` **name**: `string`
Defined in: [packages/wire/src/artifact-format.ts:16](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L16)
How messages name the artifact, such as `heap` or `segmented-trie`.
***
### magic
[Section titled “magic”](#magic)
> `readonly` **magic**: `Uint8Array`
Defined in: [packages/wire/src/artifact-format.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L18)
The four bytes that identify the owning module.
***
### payloadVersion
[Section titled “payloadVersion”](#payloadversion)
> `readonly` **payloadVersion**: `number`
Defined in: [packages/wire/src/artifact-format.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L20)
The one payload version this release writes and reads. The number is the module’s; the comparison is wire’s.
***
### kindTags
[Section titled “kindTags”](#kindtags)
> `readonly` **kindTags**: `Readonly`<`Record`<`Kind`, `number`>>
Defined in: [packages/wire/src/artifact-format.ts:22](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L22)
The byte each kind is written as. A tag is part of the wire contract, so it is never reused or renumbered.
***
### sectionTags
[Section titled “sectionTags”](#sectiontags)
> `readonly` **sectionTags**: readonly `number`\[]
Defined in: [packages/wire/src/artifact-format.ts:24](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L24)
The section tags the module reads. Any other tag is validated and skipped without a copy.
***
### wrongFormatHint?
[Section titled “wrongFormatHint?”](#wrongformathint)
> `readonly` `optional` **wrongFormatHint?**: `string`
Defined in: [packages/wire/src/artifact-format.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L26)
Where a value that is not bytes belongs, appended to the `wrong-format` message.
***
### parseError
[Section titled “parseError”](#parseerror)
> `readonly` **parseError**: (`code`, `detail`) => `Failure`
Defined in: [packages/wire/src/artifact-format.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L28)
Builds the module’s parse error from the code it owns for a wire failure reason.
#### Parameters
[Section titled “Parameters”](#parameters)
##### code
[Section titled “code”](#code)
[`WireFailureCode`](/reference/knotkit/wire/type-aliases/wirefailurecode/)
##### detail
[Section titled “detail”](#detail)
`string`
#### Returns
[Section titled “Returns”](#returns)
`Failure`
***
### serializationCodes
[Section titled “serializationCodes”](#serializationcodes)
> `readonly` **serializationCodes**: [`WireSerializationCodeMap`](/reference/knotkit/wire/type-aliases/wireserializationcodemap/)<`InvalidInputCode`>
Defined in: [packages/wire/src/artifact-format.ts:30](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L30)
The module’s translation of each wire caller-contract code raised while writing.
***
### invalidInputError
[Section titled “invalidInputError”](#invalidinputerror)
> `readonly` **invalidInputError**: (`code`, `detail`) => [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
Defined in: [packages/wire/src/artifact-format.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L32)
Builds the module’s invalid-input error from a translated code.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### code
[Section titled “code”](#code-1)
`InvalidInputCode`
##### detail
[Section titled “detail”](#detail-1)
`string`
#### Returns
[Section titled “Returns”](#returns-1)
[`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
# ArtifactPayload
Defined in: [packages/wire/src/artifact-format.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L36)
The module-owned bytes of an artifact: its opaque header and its tagged sections.
## Properties
[Section titled “Properties”](#properties)
### packageHeader
[Section titled “packageHeader”](#packageheader)
> `readonly` **packageHeader**: `Uint8Array`
Defined in: [packages/wire/src/artifact-format.ts:37](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L37)
***
### sections
[Section titled “sections”](#sections)
> `readonly` **sections**: readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
Defined in: [packages/wire/src/artifact-format.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L38)
# ArtifactSerializeOptions
Defined in: [packages/wire/src/artifact-format.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L42)
Optional behavior shared by every artifact writer.
## Properties
[Section titled “Properties”](#properties)
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/wire/src/artifact-format.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/artifact-format.ts#L44)
Add and populate a CRC-32 integrity section.
# ElementCodec
Defined in: [packages/wire/src/element-codec.ts:9](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L9)
An injective, pure byte codec supplied when a structure stores generic values.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
## Properties
[Section titled “Properties”](#properties)
### encode
[Section titled “encode”](#encode)
> `readonly` **encode**: (`value`) => `Uint8Array`
Defined in: [packages/wire/src/element-codec.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L11)
#### Parameters
[Section titled “Parameters”](#parameters)
##### value
[Section titled “value”](#value-1)
`Value`
#### Returns
[Section titled “Returns”](#returns)
`Uint8Array`
#### Throws
[Section titled “Throws”](#throws)
A codec-defined error when `value` is outside its exact domain.
***
### decode
[Section titled “decode”](#decode)
> `readonly` **decode**: (`bytes`) => `object`
Defined in: [packages/wire/src/element-codec.ts:13](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L13)
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### bytes
[Section titled “bytes”](#bytes)
`Uint8Array`
#### Returns
[Section titled “Returns”](#returns-1)
`object`
##### value
[Section titled “value”](#value-2)
> `readonly` **value**: `Value`
##### bytesRead
[Section titled “bytesRead”](#bytesread)
> `readonly` **bytesRead**: `number`
#### Throws
[Section titled “Throws”](#throws-1)
A codec-defined error when `bytes` do not begin with one encoded value.
# InjectiveElementOptions
Defined in: [packages/wire/src/element-codec.ts:39](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L39)
Controls which repeated values an injective element run accepts.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Value
[Section titled “Value”](#value)
`Value`
## Properties
[Section titled “Properties”](#properties)
### equals?
[Section titled “equals?”](#equals)
> `readonly` `optional` **equals?**: (`left`, `right`) => `boolean`
Defined in: [packages/wire/src/element-codec.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L44)
Decide whether two values that encoded to identical bytes are one value. When absent, every position must encode to distinct bytes.
#### Parameters
[Section titled “Parameters”](#parameters)
##### left
[Section titled “left”](#left)
`Value`
##### right
[Section titled “right”](#right)
`Value`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
# StateBridge
Defined in: [packages/wire/src/state-bridge.ts:20](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/state-bridge.ts#L20)
The bridge a package’s factories and serializers share to reach state that has no place in the public interface, without widening that interface and without `instanceof`-style dispatch.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### State
[Section titled “State”](#state)
`State`
## Properties
[Section titled “Properties”](#properties)
### attach
[Section titled “attach”](#attach)
> `readonly` **attach**: (`structure`, `state`) => `void`
Defined in: [packages/wire/src/state-bridge.ts:29](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/state-bridge.ts#L29)
Attach `state` to `structure` as a non-enumerable own property, so `Object.keys`, `for...in`, `JSON.stringify`, and spread copies never observe it.
#### Parameters
[Section titled “Parameters”](#parameters)
##### structure
[Section titled “structure”](#structure)
`object`
##### state
[Section titled “state”](#state-1)
`State`
#### Returns
[Section titled “Returns”](#returns)
`void`
#### Throws
[Section titled “Throws”](#throws)
With `INVALID_ARGUMENT` when `structure` is not an extensible object, or when a state is already attached.
***
### stateOf
[Section titled “stateOf”](#stateof)
> `readonly` **stateOf**: (`structure`) => `State` | `undefined`
Defined in: [packages/wire/src/state-bridge.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/state-bridge.ts#L42)
Return the state attached to `structure`, or `undefined` when it carries none. Structural: a structure produced by another copy of the package is readable here, and a foreign object is simply `undefined`, which the caller maps to its own `FOREIGN_STRUCTURE` code.
Reads the own data property only. An inherited descriptor is not state, and an accessor is neither read nor invoked, so an object cannot run caller-supplied code through a getter. A `Proxy` can still observe the descriptor read itself; the bridge narrows what an ordinary object can do, not what a hostile proxy can intercept.
#### Parameters
[Section titled “Parameters”](#parameters-1)
##### structure
[Section titled “structure”](#structure-1)
`unknown`
#### Returns
[Section titled “Returns”](#returns-1)
`State` | `undefined`
# WireEnvelope
Defined in: [packages/wire/src/envelope.ts:42](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L42)
A decoded envelope, retaining only byte copies controlled by its caller.
## Properties
[Section titled “Properties”](#properties)
### payloadVersion
[Section titled “payloadVersion”](#payloadversion)
> `readonly` **payloadVersion**: `number`
Defined in: [packages/wire/src/envelope.ts:43](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L43)
***
### packageHeader
[Section titled “packageHeader”](#packageheader)
> `readonly` **packageHeader**: `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:44](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L44)
***
### sections
[Section titled “sections”](#sections)
> `readonly` **sections**: readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
Defined in: [packages/wire/src/envelope.ts:45](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L45)
# WireEnvelopeDecodeOptions
Defined in: [packages/wire/src/envelope.ts:49](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L49)
Controls which validated sections receive an owned byte copy.
## Properties
[Section titled “Properties”](#properties)
### retainSection?
[Section titled “retainSection?”](#retainsection)
> `readonly` `optional` **retainSection?**: (`tag`) => `boolean`
Defined in: [packages/wire/src/envelope.ts:51](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L51)
Retain a section when its tag is recognized by the package decoder. Defaults to every tag.
#### Parameters
[Section titled “Parameters”](#parameters)
##### tag
[Section titled “tag”](#tag)
`number`
#### Returns
[Section titled “Returns”](#returns)
`boolean`
# WireEnvelopeInput
Defined in: [packages/wire/src/envelope.ts:32](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L32)
Inputs for one canonical binary envelope.
## Properties
[Section titled “Properties”](#properties)
### magic
[Section titled “magic”](#magic)
> `readonly` **magic**: `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L33)
***
### payloadVersion
[Section titled “payloadVersion”](#payloadversion)
> `readonly` **payloadVersion**: `number`
Defined in: [packages/wire/src/envelope.ts:34](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L34)
***
### packageHeader
[Section titled “packageHeader”](#packageheader)
> `readonly` **packageHeader**: `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:35](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L35)
***
### sections
[Section titled “sections”](#sections)
> `readonly` **sections**: readonly [`WireSection`](/reference/knotkit/wire/interfaces/wiresection/)\[]
Defined in: [packages/wire/src/envelope.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L36)
***
### integrity?
[Section titled “integrity?”](#integrity)
> `readonly` `optional` **integrity?**: `boolean`
Defined in: [packages/wire/src/envelope.ts:38](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L38)
Add and populate a CRC-32 integrity section.
# WireSection
Defined in: [packages/wire/src/envelope.ts:26](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L26)
One named opaque payload section in a binary envelope.
## Properties
[Section titled “Properties”](#properties)
### tag
[Section titled “tag”](#tag)
> `readonly` **tag**: `number`
Defined in: [packages/wire/src/envelope.ts:27](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L27)
***
### bytes
[Section titled “bytes”](#bytes)
> `readonly` **bytes**: `Uint8Array`
Defined in: [packages/wire/src/envelope.ts:28](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L28)
# IntegerWidth
> **IntegerWidth** = `1` | `2` | `4` | `8`
Defined in: [packages/wire/src/primitives.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/primitives.ts#L12)
Fixed little-endian field widths: 1, 2, and 4 are uint8/16/32; 8 is a uint64 holding a safe integer.
# WireEnvelopeParts
> **WireEnvelopeParts** = `Required`<[`WireEnvelopeInput`](/reference/knotkit/wire/interfaces/wireenvelopeinput/)>
Defined in: [packages/wire/src/envelope.ts:272](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L272)
Every part of a valid envelope, in the shape [serializeEnvelope](/reference/knotkit/wire/functions/serializeenvelope/) takes back.
# WireErrorCode
> **WireErrorCode** = [`WireInvalidInputErrorCode`](/reference/knotkit/wire/type-aliases/wireinvalidinputerrorcode/)
Defined in: [packages/wire/src/errors.ts:15](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L15)
# WireFailureCode
> **WireFailureCode** = `SnakeUpper`<[`WireFailureReason`](/reference/knotkit/wire/type-aliases/wirefailurereason/)>
Defined in: [packages/wire/src/failure-reasons.ts:33](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/failure-reasons.ts#L33)
The parse-code spelling a consumer package owns for a wire failure reason.
# WireFailureFactories
> **WireFailureFactories**<`E`> = `Readonly`<`Record`<[`WireFailureReason`](/reference/knotkit/wire/type-aliases/wirefailurereason/), (`detail`) => `E`>>
Defined in: [packages/wire/src/guards.ts:12](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/guards.ts#L12)
A package-owned mapping from wire validation reasons to parse errors.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### E
[Section titled “E”](#e)
`E` *extends* [`KnotkitError`](/reference/knotkit/errors/classes/knotkiterror/)
# WireFailureReason
> **WireFailureReason** = *typeof* [`WIRE_FAILURE_REASONS`](/reference/knotkit/wire/variables/wire_failure_reasons/)\[`number`]
Defined in: [packages/wire/src/failure-reasons.ts:23](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/failure-reasons.ts#L23)
# WireInvalidInputErrorCode
> **WireInvalidInputErrorCode** = *typeof* [`WIRE_INVALID_INPUT_ERROR_CODES`](/reference/knotkit/wire/variables/wire_invalid_input_error_codes/)\[`number`]
Defined in: [packages/wire/src/errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L14)
# WireSerializationCodeMap
> **WireSerializationCodeMap**<`Code`> = `Readonly`<`Record`<[`WireInvalidInputErrorCode`](/reference/knotkit/wire/type-aliases/wireinvalidinputerrorcode/), `Code`>>
Defined in: [packages/wire/src/serialization-errors.ts:14](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/serialization-errors.ts#L14)
A package’s translation from wire’s caller-contract codes to its own closed invalid-input codes.
Declaring this record is what keeps the translation exhaustive: `Code` is the package’s own union, so deleting a code from the package’s closed list fails to typecheck here, and adding a code to `WireInvalidInputErrorCode` fails to typecheck in every package until it says what the new failure means.
## Type Parameters
[Section titled “Type Parameters”](#type-parameters)
### Code
[Section titled “Code”](#code)
`Code` *extends* `string`
# WireTamperReason
> **WireTamperReason** = *typeof* [`WIRE_TAMPER_REASONS`](/reference/knotkit/wire/variables/wire_tamper_reasons/)\[`number`]
Defined in: [packages/wire/src/envelope.ts:312](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L312)
# float64Codec
> `const` **float64Codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`number`>
Defined in: [packages/wire/src/element-codec.ts:237](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L237)
A canonical IEEE-754 codec for JavaScript numbers.
# KNOTKIT_PACKAGE_VERSION
> `const` **KNOTKIT_PACKAGE_VERSION**: `string` = `manifest.version`
Defined in: [packages/wire/src/version.ts:7](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/version.ts#L7)
The `knotkit` release that produced a serialized artifact. Serializers write it as provenance; no decoder accepts or rejects a payload by it, so an artifact outlives the release that wrote it.
# stringCodec
> `const` **stringCodec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`string`>
Defined in: [packages/wire/src/element-codec.ts:255](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L255)
A length-prefixed, strict UTF-8 codec for strings.
# uint32Codec
> `const` **uint32Codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`number`>
Defined in: [packages/wire/src/element-codec.ts:198](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L198)
An injective codec for finite unsigned 32-bit integers.
# uint64Codec
> `const` **uint64Codec**: [`ElementCodec`](/reference/knotkit/wire/interfaces/elementcodec/)<`bigint`>
Defined in: [packages/wire/src/element-codec.ts:219](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/element-codec.ts#L219)
An injective codec for unsigned 64-bit bigints.
# WIRE_ERROR_CODES
> `const` **WIRE_ERROR_CODES**: readonly [`WireErrorCode`](/reference/knotkit/wire/type-aliases/wireerrorcode/)\[]
Defined in: [packages/wire/src/errors.ts:18](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L18)
Every error code emitted by `knotkit/wire`, in stable category order.
# WIRE_FAILURE_CODES
> `const` **WIRE_FAILURE_CODES**: `Readonly`<`Record`<[`WireFailureReason`](/reference/knotkit/wire/type-aliases/wirefailurereason/), [`WireFailureCode`](/reference/knotkit/wire/type-aliases/wirefailurecode/)>>
Defined in: [packages/wire/src/failure-reasons.ts:36](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/failure-reasons.ts#L36)
Every failure reason mapped to the parse code its consumer package must own.
# WIRE_FAILURE_REASONS
> `const` **WIRE_FAILURE_REASONS**: `Readonly`<*typeof* `failureReasons`>
Defined in: [packages/wire/src/failure-reasons.ts:21](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/failure-reasons.ts#L21)
# WIRE_INVALID_INPUT_ERROR_CODES
> `const` **WIRE_INVALID_INPUT_ERROR_CODES**: `Readonly`<*typeof* `invalidInputErrorCodes`>
Defined in: [packages/wire/src/errors.ts:11](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/errors.ts#L11)
Every caller-state error code emitted by [WireInvalidInputError](/reference/knotkit/wire/classes/wireinvalidinputerror/).
# WIRE_TAMPER_REASONS
> `const` **WIRE_TAMPER_REASONS**: `Readonly`<*typeof* `tamperReasons`>
Defined in: [packages/wire/src/envelope.ts:310](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/wire/src/envelope.ts#L310)
The failure reasons [tamperEnvelope](/reference/knotkit/wire/functions/tamperenvelope/) provokes from a valid artifact alone, with no knowledge of its package.
# Knotkit API reference
## Modules
[Section titled “Modules”](#modules)
* [knotkit/bitset](/reference/knotkit/bitset/)
* [knotkit/bitset/wire](/reference/knotkit/bitset/wire/)
* [knotkit/cache](/reference/knotkit/cache/)
* [knotkit/cas](/reference/knotkit/cas/)
* [knotkit/combinatorics](/reference/knotkit/combinatorics/)
* [knotkit/deque](/reference/knotkit/deque/)
* [knotkit/disjoint-set](/reference/knotkit/disjoint-set/)
* [knotkit/disjoint-set/wire](/reference/knotkit/disjoint-set/wire/)
* [knotkit/distance](/reference/knotkit/distance/)
* [knotkit/distribution](/reference/knotkit/distribution/)
* [knotkit/e-graph](/reference/knotkit/e-graph/)
* [knotkit/errors](/reference/knotkit/errors/)
* [knotkit/evolution](/reference/knotkit/evolution/)
* [knotkit/frequency-table](/reference/knotkit/frequency-table/)
* [knotkit/graph](/reference/knotkit/graph/)
* [knotkit/graph/wire](/reference/knotkit/graph/wire/)
* [knotkit/hash](/reference/knotkit/hash/)
* [knotkit/hash/wire](/reference/knotkit/hash/wire/)
* [knotkit/heap](/reference/knotkit/heap/)
* [knotkit/heap/wire](/reference/knotkit/heap/wire/)
* [knotkit/hypothesis-test](/reference/knotkit/hypothesis-test/)
* [knotkit/interval-index](/reference/knotkit/interval-index/)
* [knotkit/inverted-index](/reference/knotkit/inverted-index/)
* [knotkit/key-encoding](/reference/knotkit/key-encoding/)
* [knotkit/ordered-map](/reference/knotkit/ordered-map/)
* [knotkit/prefix-index](/reference/knotkit/prefix-index/)
* [knotkit/prng](/reference/knotkit/prng/)
* [knotkit/rate-limit](/reference/knotkit/rate-limit/)
* [knotkit/sampling](/reference/knotkit/sampling/)
* [knotkit/scalar-sketch](/reference/knotkit/scalar-sketch/)
* [knotkit/scalar-sketch/wire](/reference/knotkit/scalar-sketch/wire/)
* [knotkit/snapshot-set](/reference/knotkit/snapshot-set/)
* [knotkit/snapshot-set/wire](/reference/knotkit/snapshot-set/wire/)
* [knotkit/sorted-block](/reference/knotkit/sorted-block/)
* [knotkit/sorted-block/wire](/reference/knotkit/sorted-block/wire/)
* [knotkit/sorted-merge](/reference/knotkit/sorted-merge/)
* [knotkit/static-filter](/reference/knotkit/static-filter/)
* [knotkit/static-filter/wire](/reference/knotkit/static-filter/wire/)
* [knotkit/term-index](/reference/knotkit/term-index/)
* [knotkit/trie](/reference/knotkit/trie/)
* [knotkit/trie/wire](/reference/knotkit/trie/wire/)
* [knotkit/wire](/reference/knotkit/wire/)