Skip to content

Defined in: packages/sampling/src/reservoir-sampler.ts:19

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<Dog> must not be assignable to ReservoirSampler<Animal> — 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.

T

readonly kind: "reservoir-sampler"

Defined in: packages/sampling/src/reservoir-sampler.ts:21

Serializable identifier for this sampler implementation.


readonly capacity: number

Defined in: packages/sampling/src/reservoir-sampler.ts:24

The maximum number of retained values.


readonly add: (value) => void

Defined in: packages/sampling/src/reservoir-sampler.ts:41

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.

T

void

With code STREAM_LIMIT_EXCEEDED when the sampler has already observed 2^32 values.

With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).


readonly addAll: (values) => void

Defined in: packages/sampling/src/reservoir-sampler.ts:54

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.

Iterable<T>

void

With code STREAM_LIMIT_EXCEEDED when the sampler reaches 2^32 observed values.

With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

seenCount(): number

Defined in: packages/sampling/src/reservoir-sampler.ts:57

The number of values observed so far. O(1).

number


snapshot(): readonly T[]

Defined in: packages/sampling/src/reservoir-sampler.ts:68

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.

readonly T[]