All files / lib/rules execute-rule-percent.js

100% Statements 19/19
100% Branches 18/18
100% Functions 4/4
100% Lines 19/19

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 427x       4x 8x 8x 8x                 4x 4x 4x   4x 12x 3x   9x 9x 9x 3x   9x           4x 3x       7x  
const idToPercent = require('../id-to-percent');
 
/* eslint no-nested-ternary: 0 */
function sortValuesByPercentAscending(ruleProperty, values) {
  return values.sort((a, b) => {
    const aPercent = a[ruleProperty] || 0;
    const bPercent = b[ruleProperty] || 0;
    return aPercent < bPercent
      ? -1
      : aPercent === bPercent
        ? 0
        : 1;
  });
}
 
function executeRulePercent(input, rule, values) {
  const inputPercent = idToPercent(input);
  const ruleProperty = rule.property || 'percent';
  const sortedValues = sortValuesByPercentAscending(ruleProperty, values);
  /* eslint no-param-reassign: 0 */
  const match = sortedValues.reduce((memo, value) => {
    if (memo.found) {
      return memo;
    }
    const percent = (value[ruleProperty] || 0) / 100;
    memo.accumulatedPercent += percent;
    if (inputPercent <= memo.accumulatedPercent) {
      memo.found = value;
    }
    return memo;
  }, {
    accumulatedPercent: 0.0,
    found: null,
  });
 
  if (match.found) {
    return match.found.value;
  }
}
 
module.exports = executeRulePercent;