All files / array/src isMonotone.ts

100% Statements 5/5
100% Branches 2/2
100% Functions 3/3
100% Lines 4/4

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    1x                                     5x     5x   10x      
import { Comparator } from "@benneq/comparator";
import { Predicate } from "@benneq/predicate";
import { every } from "./every";
 
/**
 * Creates a {@link Predicate} function that checks if all elements of an
 * {@link Array} are monotonic sorted according to a {@link Comparator}.
 *
 * @exmaple
 * Check if `array` is sorted
 * ```ts
 * const isMonotoneSortedByNumber = isMonotone(numberComparator);
 * const array = [1,2,3];
 * const result = isMonotoneSortedByNumber(array);
 * console.log(result); // true
 * ```
 *
 * @typeParam T - the {@link Array} value type
 * @param comparator - the {@link Comparator} to use
 * @returns the {@link Predicate}
 */
export const isMonotone = <T>(
  comparator: Comparator<T>
): Predicate<[ArrayLike<T>]> => {
  return every<T>(
    (value, index, array) =>
      !index || comparator(array[index - 1] as T, value) < 0
  );
};