# 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

### T

`T`

## Parameters

### random

[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)

Function returning values in `[0, 1)`.

### capacity

`number`

The maximum number of retained values, from 0 through 2^32 - 1.

## Returns

[`ReservoirSampler`](/reference/knotkit/sampling/interfaces/reservoirsampler/)<`T`>

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