Stats Collector Reference Source Repository

src/collectors/number/Median.js

  1. import Collector from '../Collector';
  2.  
  3. /**
  4. * A collector that captures `median`
  5. * - The numeric value separating the higher half of the ordered
  6. * sample data from the lower half. If n is odd the median is
  7. * the center value. If n is even the median is the average
  8. * of the 2 center values.
  9. */
  10. export default class Median extends Collector {
  11. constructor() {
  12. super('median', 0, ['valuesSorted']);
  13. }
  14. handleGet(state) {
  15. const len = state.valuesSorted.length;
  16. const center = Math.floor(len / 2);
  17. if (len % 2 !== 0) {
  18. return state.valuesSorted[center];
  19. } else {
  20. return (state.valuesSorted[center - 1] + state.valuesSorted[center]) / 2;
  21. }
  22. }
  23. }