Skip to content

Instantly share code, notes, and snippets.

@alexewerlof
Last active June 26, 2024 11:02
Show Gist options
  • Save alexewerlof/4f1b19e1818e9135abf83fc6180ec17b to your computer and use it in GitHub Desktop.
Save alexewerlof/4f1b19e1818e9135abf83fc6180ec17b to your computer and use it in GitHub Desktop.
/**
* Gets the index of the element in an array that corresponds to the given percentile
* @param {number} arrLength the length of the array that we want to calculate its percentile
* @param {number} p the percentile in the range [0..100] inclusive
* @returns index of the array element that corresponds to the given percentile
*/
export function percentileIndex(arrLength, p) {
const maxPossibleIndex = arrLength - 1
return Math.ceil(maxPossibleIndex * p / 100)
}
/**
* @returns the value at the nth location in the array where n is between 0 to array.length
*/
export function percentile(arr, p) {
return arr[percentileIndex(arr.length)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment