All files / object/src shallowEqual.ts

100% Statements 16/16
100% Branches 10/10
100% Functions 3/3
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 471x     29x                             21x 21x 4x     17x 5x     12x 12x   12x 2x       10x 12x       3x       7x    
const hasProperties = (
  obj: unknown
): obj is Record<string, unknown> & Array<unknown> => {
  return typeof obj === "object" && obj !== null;
};
 
/**
 *
 * @example
 * shallowEqual("", "") => true
 * shallowEqual({ a: 1 }, { a: 1 }) => true
 * shallowEqual([1,2,3], [1,2,3]) => true
 * shallowEqual({ a: 1 }, { b: 1 }) => false
 * shallowEqual([1,2], [2,3]) => false
 * shallowEqual(null, undefined) => false
 *
 * @returns `true` if both values are shallowly equal, otherwise `false`
 */
export const shallowEqual = (valueA: unknown, valueB: unknown): boolean => {
  if (Object.is(valueA, valueB)) {
    return true;
  }
 
  if (!hasProperties(valueA) || !hasProperties(valueB)) {
    return false;
  }
 
  const keysA = Object.keys(valueA);
  const keysB = Object.keys(valueB);
 
  if (keysA.length !== keysB.length) {
    return false;
  }
 
  // Test for A's keys different from B.
  for (const currentKey of keysA) {
    if (
      !(currentKey in valueB) ||
      !Object.is(valueA[currentKey], valueB[currentKey])
    ) {
      return false;
    }
  }
 
  return true;
};