Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 38 lines · 1.3 KiB · at f30ac63

// Bug: default Array.prototype.sort (lexicographic, and it sorts the caller's array in place).export type Summary = { count: number; mean: number; median: number; min: number; max: number };export type StatsErrorKind = "empty" | "not_finite" | "invalid_percentile";export class StatsError extends Error {  readonly index?: number;  constructor(    public readonly kind: StatsErrorKind,    detail: { index?: number } = {},  ) {    super(kind);    Object.assign(this, detail);  }}const check = (values: number[]): void => {  if (values.length === 0) throw new StatsError("empty");  values.forEach((v, index) => {    if (!isFinite(v)) throw new StatsError("not_finite", { index });  });};export function summarize(values: number[]): Summary {  check(values);  const s = values.sort();  const n = s.length;  const mean = s.reduce((a, b) => a + b, 0) / n;  const median = n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;  return { count: n, mean, median, min: Math.min(...s), max: Math.max(...s) };}export function percentile(values: number[], p: number): number {  check(values);  if (!(p >= 0 && p <= 100)) throw new StatsError("invalid_percentile");  const s = values.sort();  return s[Math.max(1, Math.ceil((p / 100) * s.length)) - 1];}