All files index.js

100% Statements 25/25
100% Branches 10/10
100% Functions 5/5
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55    3x       3x 12x     3x 3x   3x 12x 12x 12x   3x       3x 3x   3x 2x 6x   2x     1x 11x       1x 6x 1x         5x         1x       1x  
class Averages {
  constructor(config) {
    this.config = config || {};
  }
 
  calculate(object) {
    const total = Object.keys(object).reduce(
      (sum, key) => sum + object[key],
      0
    );
    const averages = {};
    let roundedTotal = 0;
 
    for (let key in object) {
      const value = object[key];
      averages[key] = total === 0 ? 0 : (parseInt(value, 10) / total) * 100;
      roundedTotal += Math.round(averages[key]);
    }
    return this.round(averages, roundedTotal);
  }
 
  round(averages, roundedTotal) {
    const roundedAverages = {};
    const correction = 100 - roundedTotal;
 
    if (correction === 0 || correction === 100) {
      for (let key in averages) {
        roundedAverages[key] = Math.round(averages[key]);
      }
      return roundedAverages;
    }
 
    const sortedByDecimals = Object.keys(averages).sort((key) => {
      return (
        (1 / ((averages[key] % 1) - 0.5)) * (correction / Math.abs(correction))
      );
    });
    for (let i = 0; i < Object.keys(averages).length; i++) {
      if (i < Math.abs(correction)) {
        roundedAverages[sortedByDecimals[i]] = Math.round(
          (averages[sortedByDecimals[i]] +=
            (0.5 * correction) / Math.abs(correction))
        );
      } else {
        roundedAverages[sortedByDecimals[i]] = Math.round(
          averages[sortedByDecimals[i]]
        );
      }
    }
    return roundedAverages;
  }
}
 
module.exports = Averages;