All files / object is-shallow-equal.ts

100% Statements 7/7
100% Branches 11/11
100% Functions 2/2
100% Lines 7/7

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                            14x 3x   11x 4x   7x 7x   9x      
import { isObject } from '../guard';
 
/**
 * Checks whether two values are equal at the first level, with `Object.is`: skips an update when a new object carries the
 * same values as the previous one.
 *
 * @param a - The first value.
 * @param b - The second value.
 * @returns `true` when both values are shallowly equal; nested objects are compared by reference.
 * @example
 * isShallowEqual({ x: 1, y: 2 }, { y: 2, x: 1 }); // true
 * isShallowEqual({ p: { x: 1 } }, { p: { x: 1 } }); // false
 */
export function isShallowEqual(a: unknown, b: unknown): boolean {
  if (Object.is(a, b)) {
    return true;
  }
  if (!isObject(a) || !isObject(b) || Array.isArray(a) !== Array.isArray(b)) {
    return false;
  }
  const keys = Object.keys(a);
  return (
    keys.length === Object.keys(b).length &&
    keys.every((key) => Object.hasOwn(b, key) && Object.is(Reflect.get(a, key), Reflect.get(b, key)))
  );
}