UNPKG

stats-percentile

Version:
55 lines (42 loc) 1.34 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global._stats_percentile = factory()); }(this, (function () { 'use strict'; function swap(data, i, j) { if (i === j) { return; } var tmp = data[j]; data[j] = data[i]; data[i] = tmp; } function partition(data, start, end) { var i, j; for (i = start + 1, j = start; i < end; i++) { if (data[i] < data[start]) { swap(data, i, ++j); } } swap(data, start, j); return j; } function findK(data, start, end, k) { while (start < end) { var pos = partition(data, start, end); if (pos === k) { return data[k]; } if (pos > k) { end = pos; } else { start = pos + 1; } } } // Calculate n-th percentile of 'data' using Nearest Rank Method // http://en.wikipedia.org/wiki/Percentile#The_Nearest_Rank_method function index (data, n) { return findK(data.slice(), 0, data.length, Math.ceil(data.length * n / 100) - 1); } return index; })));