All files / object is-deep-equal.ts

100% Statements 28/28
100% Branches 48/48
100% Functions 7/7
100% Lines 26/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          30x 2x   28x 3x   25x 3x   22x 4x   3x     18x 3x 3x 18x   15x 15x   22x         58x 16x   42x 9x   33x 33x 3x   30x 58x                           35x    
import { isObject } from '../guard';
 
type Visited = WeakMap<object, WeakSet<object>>;
 
function equalObjects(a: object, b: object, visited: Visited): boolean {
  if (a instanceof Date && b instanceof Date) {
    return Object.is(a.getTime(), b.getTime());
  }
  if (a instanceof RegExp && b instanceof RegExp) {
    return a.source === b.source && a.flags === b.flags;
  }
  if (a instanceof Set && b instanceof Set) {
    return a.size === b.size && [...a].every((item: unknown) => b.has(item));
  }
  if (a instanceof Map && b instanceof Map) {
    return (
      a.size === b.size &&
      [...a].every(([key, value]: readonly [unknown, unknown]) => b.has(key) && equals(value, b.get(key), visited))
    );
  }
  if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
    const first = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
    const second = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
    return first.length === second.length && first.every((byte, index) => byte === second[index]);
  }
  const keys = Object.keys(a);
  return (
    keys.length === Object.keys(b).length &&
    keys.every((key) => Object.hasOwn(b, key) && equals(Reflect.get(a, key), Reflect.get(b, key), visited))
  );
}
 
function equals(a: unknown, b: unknown, visited: Visited): boolean {
  if (a === b || (Number.isNaN(a) && Number.isNaN(b))) {
    return true;
  }
  if (!isObject(a) || !isObject(b) || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
    return false;
  }
  const seen = visited.get(a);
  if (seen?.has(b) === true) {
    return true;
  }
  visited.set(a, (seen ?? new WeakSet()).add(b));
  return equalObjects(a, b, visited);
}
 
/**
 * Checks whether two values are equal at every depth: primitives (`NaN` equals `NaN`), arrays, objects with the same
 * prototype, `Date`, `RegExp`, `Map`, `Set` and typed arrays. Circular references work.
 *
 * @param a - The first value.
 * @param b - The second value.
 * @returns `true` when both values have the same structure and contents.
 * @example
 * isDeepEqual({ position: { x: 1 }, tags: ['a'] }, { position: { x: 1 }, tags: ['a'] }); // true
 */
export function isDeepEqual(a: unknown, b: unknown): boolean {
  return equals(a, b, new WeakMap());
}