All files / platform/app/src/utils shallowEqualIgnoringArrayOrder.ts

0% Statements 0/19
0% Branches 0/11
0% Functions 0/1
0% Lines 0/19

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                                                                                           
/**
 * Shallow equality for two flat record-shaped objects, with one twist:
 * array values are compared as unordered sets (so `[1, 2]` is equal to
 * `[2, 1]`). Scalar values are compared with strict `===`.
 *
 * Limitation: this is a *shallow* comparison. Nested objects are compared
 * by reference; this function does not recurse. It is intended for flat
 * records whose values are primitives or arrays of primitives.
 *
 * @param {object} a - First object
 * @param {object} b - Second object
 * @returns {boolean} True if the two are equal under the rules above.
 */
export function shallowEqualIgnoringArrayOrder(a, b): boolean {
  Iif (!a || !b) {
    return a === b;
  }
 
  const allKeys = new Set([...Object.keys(a), ...Object.keys(b)]);
 
  for (const key of allKeys) {
    const val1 = a[key];
    const val2 = b[key];
 
    if (Array.isArray(val1) && Array.isArray(val2)) {
      Iif (val1.length !== val2.length) {
        return false;
      }
      const s1 = new Set(val1);
      const s2 = new Set(val2);
      Iif (s1.size !== s2.size) {
        return false;
      }
      for (const v of s2.values()) {
        Iif (!s1.has(v)) {
          return false;
        }
      }
    } else Iif (val1 !== val2) {
      return false;
    }
  }
 
  return true;
}