Skip to content

Keep the k largest values of a stream

Hold a min heap of size k and replace its root whenever a larger value arrives.

import {
function minBinaryHeap<A>(order: Order<A>, items?: Iterable<A>): BinaryHeap<A>

Create a min binary heap: the smallest element per order is at the root, and pop extracts in ascending order.

@example

const heap = minBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 1

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

minBinaryHeap
,
const numberOrder: Order<number>

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.

numberOrder
} from 'knotkit/heap'
const
const k: 3
k
= 3
const
const largest: BinaryHeap<number>
largest
=
minBinaryHeap<number>(order: Order<number>, items?: Iterable<number> | undefined): BinaryHeap<number>

Create a min binary heap: the smallest element per order is at the root, and pop extracts in ascending order.

@example

const heap = minBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 1

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

minBinaryHeap
(
const numberOrder: Order<number>

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.

numberOrder
)
for (const
const latency: number
latency
of [120, 45, 300, 87, 210, 95, 410]) {
if (
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.size: number

Number of elements. O(1). The heap is empty when this is 0.

size
<
const k: 3
k
) {
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.push: (value: number) => void

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<Dog> widen into Heap<Animal> 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.

push
(
const latency: number
latency
)
} else if (
const latency: number
latency
>
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.peek: () => number

Return the extreme element without removing it. O(1).

Property syntax for the same variance reason as

push

.

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

peek
()) {
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.replaceRoot: (value: number) => number

Return the current root and replace it with the supplied value, preserving size. O(log n).

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

replaceRoot
(
const latency: number
latency
)
}
}
const
const top: number[]
top
: number[] = []
while (
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.size: number

Number of elements. O(1). The heap is empty when this is 0.

size
> 0) {
const top: number[]
top
.
Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@param ― items New elements to add to the array.

push
(
const largest: BinaryHeap<number>
largest
.
BinaryHeap<number>.pop: () => number

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

.

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

pop
())
}
const top: number[]
top
// [210, 300, 410]

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 · API reference