All files / lib/rules prep-for-comparison.js

100% Statements 18/18
100% Branches 14/14
100% Functions 3/3
100% Lines 16/16

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 2914x 14x 14x 14x     168x   168x 141x 141x 95x   27x   26x 24x 16x 16x           168x     14x  
const isString = require('lodash.isstring');
const isBoolean = require('lodash.isboolean');
const isNumber = require('lodash.isnumber');
const isObject = require('lodash.isobject');
 
function prepForComparison(value, rule, recursive = false) {
  let coercedValue = value;
  // coerce boolean/number/string to string, lowercase if case insensitive rule
  if (isBoolean(coercedValue) || isNumber(coercedValue) || isString(coercedValue)) {
    coercedValue = String(coercedValue);
    if (!rule.isCaseSensitive) {
      coercedValue = coercedValue.toLowerCase();
    }
  } else if (!recursive) {
    // if we're not in a recursive call then prep array/object values for comparison
    if (Array.isArray(coercedValue)) {
      coercedValue = coercedValue.map((val) => prepForComparison(val, rule, true));
    } else if (isObject(coercedValue)) {
      coercedValue = Object.keys(coercedValue).reduce((memo, key) => ({
        ...memo,
        [key]: prepForComparison(coercedValue[key], rule, true),
      }), {});
    }
  }
  return coercedValue;
}
 
module.exports = prepForComparison;