| import type { Distribution } from '../types.js'
|
|
|
| function quantile(sortedValues: number[], q: number): number {
|
| if (sortedValues.length === 0) return 0
|
| if (sortedValues.length === 1) return sortedValues[0]!
|
| const pos = (sortedValues.length - 1) * q
|
| const lower = Math.floor(pos)
|
| const upper = Math.ceil(pos)
|
| if (lower === upper) return sortedValues[lower]!
|
| const weight = pos - lower
|
| return sortedValues[lower]! * (1 - weight) + sortedValues[upper]! * weight
|
| }
|
|
|
| export function buildDistribution(values: number[]): Distribution | null {
|
| if (values.length === 0) return null
|
| const sorted = [...values].sort((a, b) => a - b)
|
| const total = sorted.reduce((sum, value) => sum + value, 0)
|
| return {
|
| min: sorted[0]!,
|
| max: sorted[sorted.length - 1]!,
|
| mean: total / sorted.length,
|
| p50: quantile(sorted, 0.5),
|
| p95: quantile(sorted, 0.95),
|
| p99: quantile(sorted, 0.99),
|
| }
|
| }
|
|
|
| export function clamp(value: number, min: number, max: number): number {
|
| return Math.min(max, Math.max(min, value))
|
| }
|
|
|