percentile.js 655 B

1234567891011121314151617
  1. // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
  2. // Returns the value at a given percentile in a sorted numeric array.
  3. // "Linear interpolation between closest ranks" method
  4. module.exports = function percentile(arr, p) {
  5. if (arr.length === 0) return 0;
  6. if (typeof p !== 'number') throw new TypeError('p must be a number');
  7. if (p <= 0) return arr[0];
  8. if (p >= 1) return arr[arr.length - 1];
  9. var index = arr.length * p,
  10. lower = Math.floor(index),
  11. upper = lower + 1,
  12. weight = index % 1;
  13. if (upper >= arr.length) return arr[lower];
  14. return arr[lower] * (1 - weight) + arr[upper] * weight;
  15. }