All files / array/src arrayComparator.ts

100% Statements 6/6
100% Branches 10/10
100% Functions 3/3
100% Lines 5/5

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                                            11x     11x                   11x 11x     11x      
import { Comparator } from "@benneq/comparator";
 
/**
 * Creates a {@link @benneq/comparator!Comparator} that compares the elements of two
 * {@link Array}s pairwise.
 *
 * Finds the first unequal pair and returns the result.
 *
 * If all pairs are equal the Array's `length` will be used for comparison.
 *
 * @example
 * Compare two {@link Array}s of numbers
 * ```ts
 * const numberArrayComparator = arrayComparator(numberComparator);
 * const result = numberArrayComparator([1, 1], [2]);
 * console.log(result); // 1
 * ```
 *
 * @typeParam T - the {@link @benneq/comparator!Comparator} value type
 * @param comparator - the {@link @benneq/comparator!Comparator} to use for the elements
 * @returns a {@link @benneq/comparator!Comparator} for {@link Array}s of type `T`
 */
export const arrayComparator = <T>(
  comparator: Comparator<T>
): Comparator<ArrayLike<T>> => {
  return (
    arrayA,
    arrayB,
    // internal variables:
    aLength = arrayA.length,
    bLength = arrayB.length,
    length = aLength < bLength ? aLength : bLength,
    i = 0,
    result?: number
  ) => {
    while (i < length && !result) {
      result = comparator(arrayA[i] as T, arrayB[i++] as T);
    }
 
    return result || aLength - bLength;
  };
};