Skip to content

knotkit/sampling

Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness

import {
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
} from 'knotkit/prng'
import {
function sampleIndices(random: RandomSource, populationSize: number, sampleSize: number): readonly number[]

Sample a uniform subset of 0..populationSize - 1 in ascending order.

Floyd's algorithm uses O(sampleSize) expected auxiliary space, followed by an O(sampleSize log sampleSize) canonical sort. The inputs are not mutated.

@throws ― {SamplingInvalidInputError} With code INVALID_POPULATION_SIZE when populationSize is not a safe integer in 0..2^32, or INVALID_SAMPLE_SIZE when sampleSize is not representable or exceeds the population.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

sampleIndices
,
function shuffled<T>(random: RandomSource, values: readonly T[]): readonly T[]

Return a uniformly shuffled copy of values using Fisher-Yates.

Runs in O(values.length) time and uses O(values.length) space for the copy. The input is never mutated.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

shuffled
,
function weightedChoice(random: RandomSource, weights: readonly number[]): number

Sample one index proportionally to its finite non-negative weight.

Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the largest weight keeps the cumulative sum finite without changing the distribution. The weights are not mutated.

@throws ― {SamplingInvalidInputError} With code INVALID_WEIGHT when a weight is negative or non-finite, or ZERO_TOTAL_WEIGHT when the array is empty or contains no positive weight.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

weightedChoice
} from 'knotkit/sampling'
const
const random: () => number
random
=
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
(42)
function sampleIndices(random: RandomSource, populationSize: number, sampleSize: number): readonly number[]

Sample a uniform subset of 0..populationSize - 1 in ascending order.

Floyd's algorithm uses O(sampleSize) expected auxiliary space, followed by an O(sampleSize log sampleSize) canonical sort. The inputs are not mutated.

@throws ― {SamplingInvalidInputError} With code INVALID_POPULATION_SIZE when populationSize is not a safe integer in 0..2^32, or INVALID_SAMPLE_SIZE when sampleSize is not representable or exceeds the population.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

sampleIndices
(
const random: () => number
random
, 10, 3) // three distinct indices in ascending order
shuffled<string>(random: RandomSource, values: readonly string[]): readonly string[]

Return a uniformly shuffled copy of values using Fisher-Yates.

Runs in O(values.length) time and uses O(values.length) space for the copy. The input is never mutated.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

shuffled
(
const random: () => number
random
, ['a', 'b', 'c']) // a new array; the input is untouched
function weightedChoice(random: RandomSource, weights: readonly number[]): number

Sample one index proportionally to its finite non-negative weight.

Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the largest weight keeps the cumulative sum finite without changing the distribution. The weights are not mutated.

@throws ― {SamplingInvalidInputError} With code INVALID_WEIGHT when a weight is negative or non-finite, or ZERO_TOTAL_WEIGHT when the array is empty or contains no positive weight.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

weightedChoice
(
const random: () => number
random
, [1, 2, 0]) // index 0 or 1; never 2
sampling.ts
import {
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
} from 'knotkit/prng'
import {
function reservoirSampler<T>(random: RandomSource, capacity: number): ReservoirSampler<T>

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.

@param ― random - Function returning values in [0, 1).

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

@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when capacity is not a safe integer in 0..2^32 - 1. Validation happens before the source is ever called.

reservoirSampler
} from 'knotkit/sampling'
const
const sampler: ReservoirSampler<number>
sampler
=
reservoirSampler<number>(random: RandomSource, capacity: number): ReservoirSampler<number>

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.

@param ― random - Function returning values in [0, 1).

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

@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when capacity is not a safe integer in 0..2^32 - 1. Validation happens before the source is ever called.

reservoirSampler
<number>(
function splitmix32(seed: number): () => number

Creates a deterministic 32-bit pseudorandom number generator.

Each call advances a private state by 0x9e3779b9. This constant equals floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo 2^32. Because the increment is odd, it is coprime to 2^32. The resulting Weyl sequence visits every 32-bit state once before it repeats.

The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from the

https://github.com/skeeto/hash-prospector hash-prospector

search for low avalanche bias. Its XOR-shifts and multiplications by odd integers are invertible over 32-bit values. The mixer therefore preserves the full period while diffusing nearby states across the output bits.

Math.imul and the bitwise operators keep the mixing steps in 32-bit arithmetic. The final unsigned conversion produces an integer from 0 to 2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).

The SplitMix family was introduced by Steele, Lea, and Flood in

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
(42), 3)
const sampler: ReservoirSampler<number>
sampler
.
ReservoirSampler<number>.addAll: (values: Iterable<number>) => void

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.

@throws ― {SamplingInvalidInputError} With code STREAM_LIMIT_EXCEEDED when the sampler reaches 2^32 observed values.

@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).

addAll
([1, 2, 3, 4, 5])
const sampler: ReservoirSampler<number>
sampler
.
ReservoirSampler<number>.snapshot(): readonly number[]

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.

snapshot
() // three of the five values, each retained with probability 3/5
  • pick k distinct items from a population or an index range without shuffling the whole population
  • shuffle a copy of a list reproducibly, so a rerun from the same seed yields the same order
  • pick one item in proportion to its weight, or k items in proportion to their weights without replacement
  • keep a bounded uniform sample of a stream whose length is not known in advance
  • pick two distinct items, optionally at least a minimum number of positions apart
  • replay a simulation or a generated test fixture exactly from a recorded seed
{"v":1,"box":[48.3056,94.1597,1043,437.3555],"x":{"s":"linear","lim":[-3.15,73.15],"inv":false,"g":0,"t":"Share expected from the weights (%)","tk":[[10,"10"],[20,"20"],[70,"70"],[0,"0"]]},"y":{"s":"linear","lim":[-3.15,73.15],"inv":false,"g":0,"tk":[[10,"10"],[20,"20"],[70,"70"],[0,"0"]]},"ti":"Draw shares follow the weights within 0.7 pp; weight 0 is never drawn","a":[{"k":"line","c":"#5b6b7c","s":"x","d":[0,0,3.5,3.5,7,7,10.5,10.5,14,14,17.5,17.5,21,21,24.5,24.5,28,28,31.5,31.5,35,35,38.5,38.5,42,42,45.5,45.5,49,49,52.5,52.5,56,56,59.5,59.5,63,63,66.5,66.5,70,70],"p":[89.37,423.19,135,407.44,180.63,391.7,226.26,375.96,271.88,360.22,317.51,344.47,363.14,328.73,408.77,312.99,454.4,297.24,500.02,281.5,545.65,265.76,591.28,250.01,636.91,234.27,682.54,218.53,728.17,202.79,773.79,187.04,819.42,171.3,865.05,155.56,910.68,139.81,956.31,124.07,1001.93,108.33]},{"k":"scatter","c":"#c4501b","s":"xy","d":[10,9.925,20,20.7,70,69.375,0,0],"p":[219.74,378.54,350.1,330.08,1001.93,111.14,89.37,423.19],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 10 20 70 0 Share expected from the weights (%) 10 20 70 0 weight 1: 9.9% weight 2: 20.7% weight 7: 69.4% weight 0: 0.0% Share of seeded draws (%) Draw shares follow the weights within 0.7 pp; weight 0 is never drawn
{"v":1,"box":[48.3056,122.3921,595,437.3555],"x":{"s":"linear","lim":[-3.15,73.15],"inv":false,"g":0,"t":"Share expected from the weights (%)","tk":[[10,"10"],[20,"20"],[70,"70"],[0,"0"]]},"y":{"s":"linear","lim":[-3.15,73.15],"inv":false,"g":0,"tk":[[10,"10"],[20,"20"],[70,"70"],[0,"0"]]},"ti":"Draw shares follow the weights within 0.7\npp; weight 0 is never drawn","a":[{"k":"line","c":"#5b6b7c","s":"x","d":[0,0,3.5,3.5,7,7,10.5,10.5,14,14,17.5,17.5,21,21,24.5,24.5,28,28,31.5,31.5,35,35,38.5,38.5,42,42,45.5,45.5,49,49,52.5,52.5,56,56,59.5,59.5,63,63,66.5,66.5,70,70],"p":[70.88,424.35,95.95,409.9,121.03,395.46,146.11,381.01,171.19,366.56,196.26,352.11,221.34,337.67,246.42,323.22,271.5,308.77,296.58,294.32,321.65,279.87,346.73,265.43,371.81,250.98,396.89,236.53,421.96,222.08,447.04,207.63,472.12,193.19,497.2,178.74,522.27,164.29,547.35,149.84,572.43,135.4]},{"k":"scatter","c":"#c4501b","s":"xy","d":[10,9.925,20,20.7,70,69.375,0,0],"p":[142.53,383.38,214.18,338.9,572.43,137.98,70.88,424.35],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 10 20 70 0 Share expected from the weights (%) 10 20 70 0 weight 1: 9.9% weight 2: 20.7% weight 7: 69.4% weight 0: 0.0% Share of seeded draws (%) Draw shares follow the weights within 0.7 pp; weight 0 is never drawn
{"v":1,"box":[69.3681,94.1597,796.1333,437.3555],"x":{"s":"linear","lim":[0.069,12.931],"inv":false,"g":0,"t":"Arrival position in a stream of 12","tk":[[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"],[7,"7"],[8,"8"],[9,"9"],[10,"10"],[11,"11"],[12,"12"]]},"y":{"s":"linear","lim":[-1.7116329922,1.7116329922],"inv":false,"g":0,"tk":[[-1.36930639376,"−1.37"],[0,"0"],[1.36930639376,"+1.37"]]},"ti":"12 of 12 arrival positions are kept within 2 SD of the 25% target","a":[{"k":"scatter","c":"#1d5fa6","s":"xy","d":[1,0.525,2,0.275,3,-0.675,4,-0.225,5,-0.8,6,0.175,7,1.225,8,-0.125,9,0.725,10,-0.8,11,0.05,12,-0.35],"p":[121.97,213.12,178.48,238.19,234.98,333.43,291.49,288.31,347.99,345.96,404.5,248.21,461,142.95,517.51,278.29,574.01,193.07,630.52,345.96,687.02,260.74,743.53,300.85],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 2 3 4 5 6 7 8 9 10 11 12 Arrival position in a stream of 12 −1.37 0 +1.37 Retention minus the expected 25% (percentage points) ±2 SD over 4,000 streams 12 of 12 arrival positions are kept within 2 SD of the 25% target
{"v":1,"box":[69.3681,122.3921,348.1333,437.3555],"x":{"s":"linear","lim":[0.069,12.931],"inv":false,"g":0,"t":"Arrival position in a stream of 12","tk":[[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"],[7,"7"],[8,"8"],[9,"9"],[10,"10"],[11,"11"],[12,"12"]]},"y":{"s":"linear","lim":[-1.7116329922,1.7116329922],"inv":false,"g":0,"tk":[[-1.36930639376,"−1.37"],[0,"0"],[1.36930639376,"+1.37"]]},"ti":"12 of 12 arrival positions are kept\nwithin 2 SD of the 25% target","a":[{"k":"scatter","c":"#1d5fa6","s":"xy","d":[1,0.525,2,0.275,3,-0.675,4,-0.225,5,-0.8,6,0.175,7,1.225,8,-0.125,9,0.725,10,-0.8,11,0.05,12,-0.35],"p":[89.55,231.57,111.22,254.57,132.89,341.98,154.57,300.58,176.24,353.48,197.91,263.77,219.59,167.17,241.26,291.37,262.93,213.17,284.61,353.48,306.28,275.27,327.96,312.08],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 2 3 4 5 6 7 8 9 10 11 12 Arrival position in a stream of 12 −1.37 0 +1.37 Retention minus the expected 25% (percentage points) ±2 SD over 4,000 streams 12 of 12 arrival positions are kept within 2 SD of the 25% target
  • 4,000 weighted choices with seed 42 and weights [1, 2, 7, 0].
  • Observed picks per item: 397, 828, 2775, 0.
  • The zero-weight item is ineligible. Each call draws one item independently.

Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/sampling in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
sampleIndicesreadonly number[]Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.
samplePairreadonly [number, number]Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.
sampleConstrainedPairreadonly [number, number]Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
shuffledreadonly T[]Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.
weightedChoicenumberOne index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
weightedSamplereadonly number[]k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
weightedSampleFromLogWeightsreadonly number[]The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
reservoirSamplerReservoirSampler<T>Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.

Cost per member. Open a row for every operation.

reservoirSampler 4 members
MemberCost
addO(1) amortized
addAllO(1) per value
seenCountO(1)
snapshotO(capacity)
InputTypeGet one from
randomness, consumed once per draw and never created or owned; the same source state replays the same sampleRandomSourceknotkit/prng

Every error this module throws is SamplingInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

SamplingInvalidInputError
INVALID_POPULATION_SIZE INVALID_SAMPLE_SIZE INVALID_RANGE INVALID_GAP INVALID_WEIGHT INVALID_LOG_WEIGHT ZERO_TOTAL_WEIGHT INSUFFICIENT_POSITIVE_WEIGHT INVALID_CAPACITY
Other
STREAM_LIMIT_EXCEEDED
If you need to…Use instead
a seeded random source of your own, or the sequence the draws come fromknotkit/prng
randomness an attacker must not be able to predictcrypto.getRandomValues
sample with replacementone weighted draw per item over a shared random source
keep the drawn items ordered, or evict the weakest of them as more arriveknotkit/heap
estimate how many distinct values a stream held, or how often one occurredknotkit/scalar-sketch
draw from a named distributionknotkit/distribution
test whether draws fit a distributionknotkit/hypothesis-test

Measured by the suite in packages/sampling/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/sampling
Use knotkit/sampling for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sampling'.

Exports:
- `sampleIndices` → `readonly number[]`: Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.
- `samplePair` → `readonly [number, number]`: Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.
- `sampleConstrainedPair` → `readonly [number, number]`: Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
- `shuffled` → `readonly T[]`: Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.
- `weightedChoice` → `number`: One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
- `weightedSample` → `readonly number[]`: k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
- `weightedSampleFromLogWeights` → `readonly number[]`: The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
- `reservoirSampler` → `ReservoirSampler<T>`: Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.

Inputs and their sources:
- randomness, consumed once per draw and never created or owned; the same source state replays the same sample: `RandomSource` from `knotkit/prng`

Use something else when:
- a seeded random source of your own, or the sequence the draws come from → knotkit/prng
- randomness an attacker must not be able to predict → crypto.getRandomValues
- sample with replacement → one weighted draw per item over a shared random source
- keep the drawn items ordered, or evict the weakest of them as more arrive → knotkit/heap
- estimate how many distinct values a stream held, or how often one occurred → knotkit/scalar-sketch
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test

Errors are SamplingInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/sampling.md
Types: node_modules/knotkit/sampling/ and https://knotkit.jkomyno.dev/reference/knotkit/sampling/