All files shallow-equals.ts

100% Statements 25/25
100% Branches 15/15
100% Functions 1/1
100% Lines 25/25

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 511x                                       1x 12x 12x 12x 12x 12x 3x 3x   12x 4x 4x   5x   5x 5x   12x 1x 1x   12x 6x 2x 2x 6x   2x 2x  
import { sameValue } from './same-value.ts';
 
/**
 * Compare two object for equality.  Testing goes one level deep.
 * @param objA - First object to compare
 * @param objB - Second object to compare
 * @param exclude - Array of key names to exclude from the comparison
 * @returns true if the two objects have the same members
 * @group Object
 * @category Comparison
 * @example
 * ```typescript
 * const a = \{ x: 1, y: 2 \};
 * const b = \{ x: 1, y: 2 \};
 * shallowEquals(a, b); // true
 * shallowEquals(a, \{ x: 1 \}); // false
 * shallowEquals(a, \{ x: 1, y: 3 \}); // false
 * shallowEquals(a, b, ['y']); // true
 * ```
 */
export function shallowEquals(
  objA: Record<string, unknown> | null | undefined,
  objB: Record<string, unknown> | null | undefined,
  exclude: string[] = [],
): boolean {
  if (sameValue(objA, objB)) {
    return true;
  }
 
  if (objA === null || objA === undefined || objB === null || objB === undefined) {
    return false;
  }
 
  const hash = new Set(exclude);
 
  const keysA = Object.keys(objA).filter((key) => !hash.has(key));
  const keysB = Object.keys(objB).filter((key) => !hash.has(key));
 
  if (keysA.length !== keysB.length) {
    return false;
  }
 
  for (const key of keysA) {
    if (!Object.prototype.hasOwnProperty.call(objB, key) || !sameValue(objA[key], objB[key])) {
      return false;
    }
  }
 
  return true;
}