median.js 439 B

12345678910111213141516171819
  1. 'use strict';
  2. module.exports = function median(key) {
  3. var length = this.items.length;
  4. if (key === undefined) {
  5. if (length % 2 === 0) {
  6. return (this.items[length / 2 - 1] + this.items[length / 2]) / 2;
  7. }
  8. return this.items[Math.floor(length / 2)];
  9. }
  10. if (length % 2 === 0) {
  11. return (this.items[length / 2 - 1][key] + this.items[length / 2][key]) / 2;
  12. }
  13. return this.items[Math.floor(length / 2)][key];
  14. };