All files / lib compare.ts

96.29% Statements 26/27
93.75% Branches 15/16
100% Functions 3/3
96.15% Lines 25/26

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 681x                       1x 43x 26x                 17x 17x   17x   17x 7x 7x 7x     17x       17x 2x 2x 7x 4x         17x 6x 11x       17x 25x           25x 4x       13x    
import {checkIfEqual, oneIsPrimitive} from '../util/helpers';
 
import {Difference} from '../types/lib/compare';
 
/**
 * 1. If objects are not of the same type or are primitive types, compares directly.
 * 2. Gets the keys from both objects.
 * 3. If both are arrays, checks their elements.
 * 4. Checks for keys present in both objects.
 *    If key is `execution`, omit unnecessary params.
 * 5. If all keys are checked and no differences are found, return empty object.
 */
export const compare = (source: any, target: any, path = ''): Difference => {
  if (oneIsPrimitive(source, target)) {
    return checkIfEqual(source, target)
      ? {}
      : {
          path,
          source,
          target,
        };
  }
 
  const keys1 = Object.keys(source);
  const keys2 = Object.keys(target);
 
  const allKeys = new Set([...keys1, ...keys2]);
 
  if (path === '') {
    allKeys.delete('name');
    allKeys.delete('description');
    allKeys.delete('tags');
  }
 
  Iif (path === 'initialize') {
    allKeys.delete('outputs');
  }
 
  if (path === 'execution') {
    const whitelist = ['status', 'error'];
    allKeys.forEach(value => {
      if (!whitelist.includes(value)) {
        allKeys.delete(value);
      }
    });
  }
 
  if (Array.isArray(source) && Array.isArray(target)) {
    source.forEach((_record, i) => {
      compare(source[i], target[i], path ? `${path}[${i}]` : `${i}`);
    });
  }
 
  for (const key of allKeys) {
    const result = compare(
      source[key],
      target[key],
      path ? `${path}.${key}` : key
    );
 
    if (Object.keys(result).length) {
      return result;
    }
  }
 
  return {};
};