smartnetwork/ts/helpers/stats.ts

44 lines
1008 B
TypeScript
Raw Normal View History

2022-02-16 22:28:12 +00:00
export function average(values: number[]) {
2021-04-28 13:41:55 +00:00
let total = 0;
for (let i = 0; i < values.length; i += 1) {
total += values[i];
}
return total / values.length;
}
2022-02-16 22:28:12 +00:00
export function median(values: number[]) {
2021-04-28 13:41:55 +00:00
const half = Math.floor(values.length / 2);
values.sort((a, b) => a - b);
if (values.length % 2) return values[half];
return (values[half - 1] + values[half]) / 2;
}
2022-02-16 22:28:12 +00:00
export function quartile(values: number[], percentile: number) {
2021-04-28 13:41:55 +00:00
values.sort((a, b) => a - b);
const pos = (values.length - 1) * percentile;
const base = Math.floor(pos);
const rest = pos - base;
if (values[base + 1] !== undefined) {
return values[base] + rest * (values[base + 1] - values[base]);
}
return values[base];
}
2022-02-16 22:28:12 +00:00
export function jitter(values: number[]) {
2021-04-28 13:41:55 +00:00
// Average distance between consecutive latency measurements...
let jitters = [];
for (let i = 0; i < values.length - 1; i += 1) {
jitters.push(Math.abs(values[i] - values[i + 1]));
}
return average(jitters);
}