All files / if-diff/util helpers.ts

100% Statements 37/37
100% Branches 26/26
100% Functions 7/7
100% Lines 34/34

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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85          2x 33x 28x     5x 1x     4x           2x   53x 4x     49x           2x 16x 2x     14x 4x     10x 4x     6x 1x     5x           2x 8x 8x   8x 4x 8x     4x     4x           2x 8x   8x 27x 15x   12x        
import {Difference} from '../types/compare';
 
/**
 * `If-diff` equality checker.
 */
export const checkIfEqual = (source: any, target: any) => {
  if (source === target) {
    return true;
  }
 
  if (source === '*' || target === '*') {
    return true;
  }
 
  return false;
};
 
/**
 * Checks if objects are primitive types.
 */
export const oneIsPrimitive = (source: any, target: any) => {
  // eslint-disable-next-line eqeqeq
  if (source == null || target == null) {
    return true;
  }
 
  return source !== Object(source) && target !== Object(target);
};
 
/**
 * Converts given `value` to either `1` or `0`.
 */
const convertToXorable = (value: any) => {
  if (typeof value === 'number') {
    return value !== 0 ? 1 : 0;
  }
 
  if (typeof value === 'boolean') {
    return value ? 1 : 0;
  }
 
  if (typeof value === 'string') {
    return value.length > 0 ? 1 : 0;
  }
 
  if (typeof value === 'object') {
    return 1;
  }
 
  return 0;
};
 
/**
 * If one of the `valuesToCheck` values is undefined, then set `missing`, otherwise `exists`.
 */
const setValuesIfMissing = (response: Difference) => {
  const source = convertToXorable(response.source);
  const target = convertToXorable(response.target);
 
  if (source ^ target) {
    ['source', 'target'].forEach(value => {
      response[value] = response[value] ? 'exists' : 'missing';
    });
 
    return response;
  }
 
  return response;
};
 
/**
 * Format not matching message for CLI logging.
 */
export const formatNotMatchingLog = (message: Difference) => {
  const flattenMessage = setValuesIfMissing(message);
 
  Object.keys(flattenMessage).forEach(key => {
    if (key === 'message' || key === 'path') {
      console.log(message[key]);
    } else {
      console.log(`${key}: ${message[key]}`);
    }
  });
};