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.
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”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”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”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.
import { numberOrder } from 'knotkit/heap'import { mergeSortedAsync } from 'knotkit/sorted-merge'
async function* remoteBlock(ids: readonly number[]): AsyncGenerator<number> { 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. Abreakawaitsreturn()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”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.
- 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
with the raw per-repeat timings in
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 against knotkit/sorted-merge.
When not to reach for it
Section titled “When not to reach for it”- The input is not sorted.
mergeSorteddoes not order anything; it merges under an order every input already satisfies. Sorting one input isArray.from(input).toSorted(order). - You need a keyed store. Keeping one item per key is a
Map; keeping keys ordered while they change isknotkit/ordered-map. - You need insert and remove of independent items. That is a queue or heap, not a merge —
knotkit/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.
| Export | Returns | Does |
|---|---|---|
mergeSorted | Generator<A, void, unknown> | Merges a finite collection of sorted iterables by pulling from the last emitted item's source. |
mergeSortedAsync | AsyncGenerator<Awaited<A>, 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”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<A, void, unknown>`: Merges a finite collection of sorted iterables by pulling from the last emitted item's source.
- `mergeSortedAsync` → `AsyncGenerator<Awaited<A>, 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<A>` 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”- API referenceevery type and signature
- Capability recordthis page as JSON, also in the installed package
- Edit this page on GitHubsuggest a change to the source record