All files / src/support/utils equal.ts

100% Statements 19/19
100% Branches 12/12
100% Functions 7/7
100% Lines 15/15

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                    11x           21x 19x 19x 42x 42x 42x 8x     19x   2x                 11x               11x               11x                 11x 20x  
import { each } from 'support/utils/array';
import { WH, XY, TRBL } from 'support/dom';
import { PlainObject } from 'typings';
 
/**
 * Compares two objects and returns true if all values of the passed prop names are identical, false otherwise or if one of the two object is falsy.
 * @param a Object a.
 * @param b Object b.
 * @param props The props which shall be compared.
 */
export const equal = <T extends PlainObject>(
  a: T | undefined,
  b: T | undefined,
  props: Array<keyof T>,
  propMutation?: ((value: any) => any) | null | false
): boolean => {
  if (a && b) {
    let result = true;
    each(props, (prop) => {
      const compareA = propMutation ? propMutation(a[prop]) : a[prop];
      const compareB = propMutation ? propMutation(b[prop]) : b[prop];
      if (compareA !== compareB) {
        result = false;
      }
    });
    return result;
  }
  return false;
};
 
/**
 * Compares object a with object b and returns true if both have the same property values, false otherwise.
 * Also returns false if one of the objects is undefined or null.
 * @param a Object a.
 * @param b Object b.
 */
export const equalWH = (a?: WH, b?: WH) => equal<WH>(a, b, ['w', 'h']);
 
/**
 * Compares object a with object b and returns true if both have the same property values, false otherwise.
 * Also returns false if one of the objects is undefined or null.
 * @param a Object a.
 * @param b Object b.
 */
export const equalXY = (a?: XY, b?: XY) => equal<XY>(a, b, ['x', 'y']);
 
/**
 * Compares object a with object b and returns true if both have the same property values, false otherwise.
 * Also returns false if one of the objects is undefined or null.
 * @param a Object a.
 * @param b Object b.
 */
export const equalTRBL = (a?: TRBL, b?: TRBL) => equal<TRBL>(a, b, ['t', 'r', 'b', 'l']);
 
/**
 * Compares two DOM Rects for their equality of their width and height properties
 * Also returns false if one of the DOM Rects is undefined or null.
 * @param a DOM Rect a.
 * @param b DOM Rect b.
 * @param round Whether the values should be rounded.
 */
export const equalBCRWH = (a?: DOMRect, b?: DOMRect, round?: boolean) =>
  equal<DOMRect>(a, b, ['width', 'height'], round && ((value) => Math.round(value)));