web/src/lib/utils.ts 1009 B raw
1
export function round(v: number): number {
2
  return Math.round(v * 10) / 10;
3
}
4
5
export function avg(arr: any[], fn: (d: any) => number): string {
6
  if (arr.length === 0) return '\u2014';
7
  return (arr.reduce((s, d) => s + fn(d), 0) / arr.length).toFixed(1);
8
}
9
10
export function std(values: number[]): number {
11
  if (values.length < 2) return 0;
12
  const m = values.reduce((s, v) => s + v, 0) / values.length;
13
  const variance = values.reduce((s, v) => s + (v - m) ** 2, 0) / (values.length - 1);
14
  return Math.sqrt(variance);
15
}
16
17
/** Remove outliers using the IQR method, returns filtered array */
18
export function filterOutliers(values: number[], k = 1.5): number[] {
19
  if (values.length < 4) return values;
20
  const sorted = [...values].sort((a, b) => a - b);
21
  const q1 = sorted[Math.floor(sorted.length * 0.25)];
22
  const q3 = sorted[Math.floor(sorted.length * 0.75)];
23
  const iqr = q3 - q1;
24
  const lower = q1 - k * iqr;
25
  const upper = q3 + k * iqr;
26
  return values.filter((v) => v >= lower && v <= upper);
27
}