All files / iterable/src isSorted.ts

100% Statements 7/7
100% Branches 0/0
100% Functions 3/3
100% Lines 6/6

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  1x   1x 1x                                     4x     4x   4x      
import { Comparator } from "@benneq/comparator";
import { pipe } from "@benneq/function";
import { Predicate } from "@benneq/predicate";
import { every } from "./every";
import { pairwise } from "./pairwise";
 
/**
 * Creates a {@link Predicate} function that checks if all elements of an
 * {@link Iterable} are sorted according to a {@link Comparator}.
 *
 * @exmaple
 * Check if `iterable` is sorted
 * ```ts
 * const isSortedByNumber = isSorted(numberComparator);
 * const iterable = [1,2,2,3];
 * const result = isSortedByNumber(iterable);
 * console.log(result); // true
 * ```
 *
 * @typeParam T - the {@link Iterable} value type
 * @param comparator - the {@link Comparator} to use
 * @returns the {@link Predicate}
 */
export const isSorted = <T>(
  comparator: Comparator<T>
): Predicate<[Iterable<T>]> => {
  return pipe(
    pairwise()<T>,
    every<[T, T]>(([a, b]) => comparator(a, b) <= 0)
  );
};