Percentile and Quantile Calculation

Compute percentiles and quantiles with linear interpolation on a copied sorted array, validating bounds and numeric input.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
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 === upper short-circuits the flow with an early return when 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

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.