js 三个数据求百分比之和需等于100%

116 阅读1分钟
const roundPercentageTotals = numArr => {
      // Total of all numbers passed.
      var total = numArr[0] + numArr[1] + numArr[2];
      if (total === 0) {
        return [0, 0, 0]
      }
      // Percentage representations of each number (out of 100).
      var num1Percent = Math.round((numArr[0] / total) * 100);
      var num2Percent = Math.round((numArr[1] / total) * 100);
      var num3Percent = Math.round((numArr[2] / total) * 100);
      // Total percent of the 3 numbers combined (doesnt always equal 100%).
      var totalPercentage = num1Percent + num2Percent + num3Percent;
      function getLargestNumInArrayIndex(array) {
        return array.indexOf(Math.max.apply(Math, array));
      }
      // If not 100%, then we need to work around it by subtracting from the largest number (not as accurate but works out).
      if (totalPercentage != 100) {
        // Get the index of the largest number in the array.
        var index = getLargestNumInArrayIndex(numArr);
        // Take the difference away from the largest number.
        numArr[index] = numArr[index] - (totalPercentage - 100);
        // Re-run this method recursively, until we get a total percentage of 100%.
        return roundPercentageTotals(numArr);
      }
      // Return the percentage version of the array passed in.
      return [num1Percent, num2Percent, num3Percent];
    };