All files deepEqual.ts

75% Statements 27/36
63.89% Branches 23/36
100% Functions 2/2
96.15% Lines 25/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 62 63 64 65 667x 7x                                                             7x     25x   13x 13x 7x 7x 7x 7x 4x 4x 4x 4x 5x   4x   3x 3x 3x 3x 3x 3x 3x   3x       13x    
import { type } from './type';
import { isFunction, isPromise, isArray, isObject } from './index';
 
/**
 * Compares two values recursively.
 * @warning Soft mode is relative expensive operation.
 * @description
 * The function has two modes `soft` and `hard` soft mode ignores array order hard mode preserves array order
 *  - `Soft mode` ignore array order.
 * @param valueA - anything
 * @param valueB - anything
 * @example
 *    P.deepEquals({
 *        data: 1,
 *        super: [{ id: 1, name: "Tom" }, { id: 2, name: "Martin" }]
 *    }, {
 *        data: 1,
 *        super: [{ id: 2, name: "Martin" }, { id: 1, name: "Tom" }]
 *    }) // false super property is not equal
 *
 *    P.deepEquals({
 *        data: 1,
 *        super: [{ id: 1, name: "Tom" }, { id: 2, name: "Martin" }]
 *    }, {
 *        data: 1,
 *        super: [{ id: 2, name: "Martin" }, { id: 1, name: "Tom" }]
 *    }, 'soft') // true Ignores array order
 *
 *
 * @param mode - array comparison mode
 * @category Utility
 */
export function deepEqual(
  valueA: unknown,
  valueB: unknown,
  mode: 'soft' | 'hard' = 'hard'
): boolean {
  const compare = (a: unknown, b: unknown) => {
    if (a === b) return true;
    Iif (type(a) !== type(b)) return false;
    Iif (isFunction(a) && isFunction(b)) a.toString() === b.toString();
    Iif (isPromise(a) && isPromise(b)) return a === b;
    if (isArray(a) && isArray(b)) {
      Iif (a.length !== b.length) return false;
      const aArray = mode === 'hard' ? a : a;
      const bArray = mode === 'hard' ? b : b;
      for (const index in aArray) {
        Iif (!deepEqual(aArray[index], bArray[index])) return false;
      }
      return true;
    }
    Eif (isObject(a) && isObject(b)) {
      const aKeys = Object.keys(a);
      const bKeys = Object.keys(b);
      Iif (aKeys.length !== bKeys.length) return false;
      Iif (!deepEqual(aKeys, bKeys)) return false;
      for (const aKey of aKeys) {
        Iif (!deepEqual(a[aKey], b[aKey])) return false;
      }
      return true;
    }
    return false;
  };
  return compare(valueA, valueB);
}