Histogram Quantile Buckets
Record observations into cumulative histogram buckets and interpolate a quantile within the crossing bucket.
Code
export interface Histogram { readonly bounds: readonly number[]; readonly counts: readonly number[]; readonly total: number; }
export function observe(bounds: readonly number[], samples: readonly number[]): Histogram {
const sorted = [...bounds].sort((a, b) => a - b);
const cumulative = new Array<number>(sorted.length + 1).fill(0);
for (const sample of samples) {
let i = 0;
while (i < sorted.length && sample > (sorted[i] as number)) i += 1;
cumulative[i] += 1;
}
for (let i = 1; i < cumulative.length; i++) cumulative[i] += cumulative[i - 1] as number;
return { bounds: sorted, counts: cumulative, total: samples.length };
}
export function quantile(hist: Histogram, q: number): number {
if (q < 0 || q > 1) throw new RangeError('q must be in [0, 1]');
const target = q * hist.total;
let prev = 0;
for (let i = 0; i < hist.counts.length; i++) {
const count = hist.counts[i] as number;
if (count >= target) {
const upper = i < hist.bounds.length ? (hist.bounds[i] as number) : prev * 2;
const lower = i === 0 ? 0 : (hist.bounds[i - 1] as number);
const bucketCount = count - prev;
if (bucketCount === 0) return upper;
return lower + ((target - prev) / bucketCount) * (upper - lower);
}
prev = count;
}
return hist.bounds[hist.bounds.length - 1] ?? 0;
}How the snippet works
Count the functions observe and quantile as the entire surface area of Histogram Quantile Buckets.
The core work runs in nested loops — outer for (const sample of samples), inner while (i < sorted.length && sample > (sorted[i] as number)) i += 1;. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
The result comes back as an object carrying sorted, cumulative.
What to watch for
- The guard
q < 0 || q > 1short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Signature: export function observe(bounds: readonly number[], samples: readonly number[])
Import observe from the file and call it — the rest of the code is implementation detail.
The call returns sorted, cumulative — destructure what you need at the call site.
Statements that matter
const sorted = [...bounds].sort((a, b) => a - b);
return hist.bounds[hist.bounds.length - 1] ?? 0;
for (let i = 1; i < cumulative.length; i++) cumulative[i] += cumulative[i - 1] as number;
Interactive Tools for This Topic
FAQ
- Does `observe` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Does the code validate its input?
- The code refuses to continue: `RangeError` is thrown while the state is still recoverable.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `observe`, `quantile` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.