Percentile and Quantile Calculation
Compute percentiles and quantiles with linear interpolation on a copied sorted array, validating bounds and numeric input.
Code
export function percentile(values: readonly number[], p: number): number {
if (!Array.isArray(values) || values.length === 0) {
throw new RangeError("values must be a non-empty array");
}
if (!Number.isFinite(p) || p < 0 || p > 100) {
throw new RangeError("p must be between 0 and 100");
}
if (!values.every(Number.isFinite)) {
throw new TypeError("values must be finite numbers");
}
const sorted = [...values].sort((a, b) => a - b);
const index = (sorted.length - 1) * (p / 100);
const lower = Math.floor(index);
const upper = Math.ceil(index);
if (lower === upper) return sorted[lower];
return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower);
}
export function quantile(values: readonly number[], q: number): number {
if (!Number.isFinite(q) || q < 0 || q > 1) {
throw new RangeError("q must be between 0 and 1");
}
return percentile(values, q * 100);
}How the snippet works
Count the functions index, percentile and quantile as the entire surface area of Percentile and Quantile Calculation.
RangeError and TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
Points of care
- The guard
lower === uppershort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Entry signature: export function percentile(values: readonly number[], p: number)
percentile is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
const sorted = [...values].sort((a, b) => a - b);
return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower);
throw new RangeError("values must be a non-empty array");
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.
FAQ
- Does the code validate its input?
- The code throws `RangeError` and `TypeError` — the guard `lower === upper` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `index`, `percentile`, `quantile` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.