Skip to content

knotkit/interval-index

Indexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range

import {
function augmentedRedBlackIntervalIndex<K, V>(order: Order<K>, initialEntries?: Iterable<IntervalInput<K, V>>): IntervalIndex<K, V>

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).

@throws ― {IntervalIndexInvalidInputError} With INVALID_INTERVAL when an initial entry's start sorts after its end.

@see ― Cormen , Leiserson, Rivest, and Stein, Introduction to Algorithms, 3rd ed., section 14.3, "Interval trees".

augmentedRedBlackIntervalIndex
} from 'knotkit/interval-index'
import {
function compareBytes(left: Uint8Array, right: Uint8Array): -1 | 0 | 1

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<Uint8Array> 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.

compareBytes
} from 'knotkit/key-encoding'
const
const key: (text: string) => Uint8Array
key
= (
text: string
text
: string):
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
=> new
var TextEncoder: new () => TextEncoder

The TextEncoder interface takes a stream of code points as input and emits a stream of UTF-8 bytes.

MDN Reference

An implementation of the WHATWG Encoding Standard TextEncoder API. All instances of TextEncoder only support UTF-8 encoding.

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');

TextEncoder
().
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
(
text: string
text
)
// Level-0 tables, each routed by its [minKey, maxKey] fence pointers.
const
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
=
augmentedRedBlackIntervalIndex<Uint8Array<ArrayBufferLike>, string>(order: Order<Uint8Array<ArrayBufferLike>>, initialEntries?: Iterable<IntervalInput<Uint8Array<ArrayBufferLike>, string>> | undefined): IntervalIndex<Uint8Array<ArrayBufferLike>, string>

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).

@throws ― {IntervalIndexInvalidInputError} With INVALID_INTERVAL when an initial entry's start sorts after its end.

@see ― Cormen , Leiserson, Rivest, and Stein, Introduction to Algorithms, 3rd ed., section 14.3, "Interval trees".

augmentedRedBlackIntervalIndex
<
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
, string>(
function compareBytes(left: Uint8Array, right: Uint8Array): -1 | 0 | 1

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<Uint8Array> 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.

compareBytes
)
const
const first: number
first
=
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.add: (start: Uint8Array<ArrayBufferLike>, end: Uint8Array<ArrayBufferLike>, value: string) => number

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.

@throws ― {IntervalIndexInvalidInputError} With INVALID_INTERVAL when start sorts after end.

add
(
const key: (text: string) => Uint8Array
key
('apple'),
const key: (text: string) => Uint8Array
key
('cherry'), 'sst-1')
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.add: (start: Uint8Array<ArrayBufferLike>, end: Uint8Array<ArrayBufferLike>, value: string) => number

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.

@throws ― {IntervalIndexInvalidInputError} With INVALID_INTERVAL when start sorts after end.

add
(
const key: (text: string) => Uint8Array
key
('banana'),
const key: (text: string) => Uint8Array
key
('date'), 'sst-2')
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.add: (start: Uint8Array<ArrayBufferLike>, end: Uint8Array<ArrayBufferLike>, value: string) => number

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.

@throws ― {IntervalIndexInvalidInputError} With INVALID_INTERVAL when start sorts after end.

add
(
const key: (text: string) => Uint8Array
key
('fig'),
const key: (text: string) => Uint8Array
key
('grape'), 'sst-3')
// A point read probes every table whose fences hold the key, oldest start first.
const
const probes: string[]
probes
= [...
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.atPoint: (point: Uint8Array<ArrayBufferLike>) => IterableIterator<IntervalEntry<Uint8Array<ArrayBufferLike>, string>>

Walk every entry whose interval holds point: start <= point <= end under the order.

@throws ― {IntervalIndexInvalidInputError} With MODIFIED_DURING_ITERATION on advancement after an add, a successful delete, or a clear of a nonempty index.

atPoint
(
const key: (text: string) => Uint8Array
key
('blueberry'))].
Array<IntervalEntry<Uint8Array<ArrayBufferLike>, string>>.map<string>(callbackfn: (value: IntervalEntry<Uint8Array<ArrayBufferLike>, string>, index: number, array: IntervalEntry<Uint8Array<ArrayBufferLike>, string>[]) => string, thisArg?: any): string[]

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

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

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

map
((
entry: IntervalEntry<Uint8Array<ArrayBufferLike>, string>
entry
) =>
entry: IntervalEntry<Uint8Array<ArrayBufferLike>, string>
entry
.
IntervalEntry<Uint8Array<ArrayBufferLike>, string>.value: string
value
) // ['sst-1', 'sst-2']
// A compaction of [cherry, fig] must read every table overlapping it; touching endpoints overlap.
const
const inputs: string[]
inputs
= [...
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.overlapping: (start: Uint8Array<ArrayBufferLike>, end: Uint8Array<ArrayBufferLike>) => IterableIterator<IntervalEntry<Uint8Array<ArrayBufferLike>, string>>

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.

@throws ― {IntervalIndexInvalidInputError} 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.

overlapping
(
const key: (text: string) => Uint8Array
key
('cherry'),
const key: (text: string) => Uint8Array
key
('fig'))].
Array<IntervalEntry<Uint8Array<ArrayBufferLike>, string>>.map<string>(callbackfn: (value: IntervalEntry<Uint8Array<ArrayBufferLike>, string>, index: number, array: IntervalEntry<Uint8Array<ArrayBufferLike>, string>[]) => string, thisArg?: any): string[]

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

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

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

map
((
entry: IntervalEntry<Uint8Array<ArrayBufferLike>, string>
entry
) =>
entry: IntervalEntry<Uint8Array<ArrayBufferLike>, string>
entry
.
IntervalEntry<Uint8Array<ArrayBufferLike>, string>.value: string
value
) // ['sst-1', 'sst-2', 'sst-3']
// Compaction retires a table by the id add returned.
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.delete: (id: number) => boolean

Remove the entry with id and report whether it existed.

delete
(
const first: number
first
) // true
const tables: IntervalIndex<Uint8Array<ArrayBufferLike>, string>
tables
.
IntervalIndex<Uint8Array<ArrayBufferLike>, string>.size: number

Number of stored entries.

size
// 2
interval-index.ts
  • 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
FactoryChoose whenCost
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 hundredone 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

ExportReturnsDoes
augmentedRedBlackIntervalIndexIntervalIndex<K, V>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.
sortedArrayIntervalIndexIntervalIndex<K, V>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
MemberCost
buildO(n log n)
sizeO(1)
addO(log n)
deleteO(log n)
hasO(1)
getO(1)
atPointO(min(n, (k + 1) log n)) for k entries reported
overlappingO(min(n, (k + 1) log n)) for k entries reported
entriesO(n)
clearO(1)
sortedArrayIntervalIndex 10 members
MemberCost
buildO(n log n)
sizeO(1)
addO(1) amortized; an add whose start sorts before the last stored start defers an O(n log n) rebuild to the next query
deleteO(1) amortized, O(n) when half the entries are deleted; nonempty queries rebuild prefix maxima in O(n) after deletions alone
hasO(1)
getO(1)
atPointO(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
overlappingO(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
entriesO(n) once settled
clearO(1)
InputTypeGet one from
key orderOrder<K>knotkit/heap

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
If you need to…Use instead
look up, rank, or scan single keys rather than rangesknotkit/ordered-map
membership or range counts over unsigned 32-bit integer idsknotkit/bitset
a compact immutable block of sorted byte-keyed entries with seeksknotkit/sorted-block
the longest stored prefix of a delimiter-separated keyknotkit/trie
overlap queries over rectangles or boxes in two or more dimensionsan R-tree library such as rbush

Measured by the suite in packages/interval-index/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/interval-index
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<K, V>`: 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<K, V>`: 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<K>` 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/