# Sample a stream of unknown length

> A reservoir sampler keeps a uniform sample of fixed size, however many items pass through.

**Few items**

```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'

const sampler = reservoirSampler<string>(splitmix32(7), 3)

for (const request of ['GET /', 'GET /a', 'POST /b', 'GET /c', 'GET /d', 'PUT /e']) {
  sampler.add(request)
}

sampler.snapshot() // ['PUT /e', 'GET /c', 'POST /b']
```

**Thousands of items**

```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'

const sampler = reservoirSampler<number>(splitmix32(7), 5)

// 50,000 requests, and no count kept anywhere else.
for (let index = 0; index < 50_000; index += 1) {
  sampler.add(index)
}

const sample = sampler.snapshot()

sample // [9113, 47886, 47206, 27133, 11142], five of the 50,000, however long the stream ran
new Set(sample).size // 5, no item appears twice
```

Every item seen so far has the same chance of being in the sample. Memory is the sample size, not the stream length.

**Modules:** [`knotkit/sampling`](/modules/sampling/) · [`knotkit/prng`](/modules/prng/) · [API reference](/reference/knotkit/sampling/)
