Reservoir Sampling For Streams

Uniformly sample a fixed number of items from arrays or one-pass iterables using reservoir sampling with an injectable random source.

JavascriptData Integrity

Code

javascriptsnippet
31 lines
export function reservoirSample(items, size, random = Math.random) {
  if (!Number.isInteger(size) || size < 0) {
    throw new RangeError("size must be a non-negative integer");
  }
  if (size === 0) return [];
  const reservoir = items.slice(0, size);
  for (let index = size; index < items.length; index += 1) {
    const candidate = Math.floor(random() * (index + 1));
    if (candidate < size) reservoir[candidate] = items[index];
  }
  return reservoir;
}

export function* reservoirStream(iterable, size, random = Math.random) {
  if (!Number.isInteger(size) || size < 0) {
    throw new RangeError("size must be a non-negative integer");
  }
  if (size === 0) return;
  const reservoir = [];
  let seen = 0;
  for (const item of iterable) {
    if (seen < size) {
      reservoir.push(item);
    } else {
      const candidate = Math.floor(random() * (seen + 1));
      if (candidate < size) reservoir[candidate] = item;
    }
    seen += 1;
  }
  yield* reservoir;
}

How it works

Count the function reservoirSample as the entire surface area of Reservoir Sampling For Streams.

Iteration is nested: for (let index = size; index < items.length; index += 1) frames the pass, for (const item of iterable) does the per-item step. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • The guard size === 0 short-circuits the flow with an early return when its condition holds.

Using it

The main signature reads export function reservoirSample(items, size, random = Math.random)

reservoirSample is the public entry point; everything else in the file exists to support it.

Key statements

throw new RangeError("size must be a non-negative integer");
for (let index = size; index < items.length; index += 1) {
const candidate = Math.floor(random() * (index + 1));
if (candidate < size) reservoir[candidate] = items[index];
}
if (size === 0) return [];

Interactive Tools for This Topic

FAQ

Does `reservoirSample` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What happens if the preconditions do not hold?
It throws `RangeError` before any real work runs, via the guard `size === 0` — handle it at the call site or let it propagate deliberately.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `reservoirSample` at load time.