All files / comparator/src stringComparator.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 3/3
100% Lines 3/3

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                                        5x     5x 8x    
import { DropFirst } from "@benneq/object";
import { Comparator } from "./_types";
 
type StringLocaleCompareArgs = DropFirst<Parameters<string["localeCompare"]>>;
 
/**
 * Creates a {@link Comparator} that orders `string` values by their natural
 * order, i.e. `'a' < 'aa' < 'ab'`.
 *
 * @example
 * Sort an Array of string values
 * ```ts
 * const array = ["ba", "aa", "ab"];
 * array.sort(stringComparator());
 * console.log(array); // ["aa", "ab", "ba"]
 * ```
 *
 * @param localeCompareArgs - the arguments passed to {@link String.prototype.localeCompare}
 * @returns a {@link Comparator} for string values
 */
export const stringComparator = (
  ...localeCompareArgs: StringLocaleCompareArgs
): Comparator<string> => {
  return (stringA, stringB) =>
    stringA.localeCompare(stringB, ...localeCompareArgs);
};