index/functions/percentileIndexCalculation.md
percentileIndexCalculation(
sortedArray,percentile):number
Calculate percentile index in a sorted array
Computes the array index corresponding to a given percentile (0-100). Uses linear interpolation for fractional positions.
Consolidates 3 occurrences of percentile calculations in monitoring metrics.
sorted array
Parameters
| Parameter | Type | Description |
|---|---|---|
sortedArray | number[] | Array of numbers, must be sorted in ascending order |
percentile | number | Percentile value from 0 to 100 (e.g., 95 for 95th percentile) |
sorted array
Returns
number
The array index, or -1 if array is empty
Throws
Error if percentile is outside [0, 100] or array is not sorted
Example
// Get 95th percentile from latency measurements
const latencies = [10, 25, 50, 75, 100, 150, 200];
const p95Index = percentileIndexCalculation(latencies, 95);
// Returns index 6 (value 200, or interpolated between 150-200)
// Median (50th percentile)
const medianIndex = percentileIndexCalculation(latencies, 50);
// Returns index 3 (value 75)
// Min/Max
const minIndex = percentileIndexCalculation(latencies, 0); // 0
const maxIndex = percentileIndexCalculation(latencies, 100); // 6