Comparators

Functions for comparing two elements of arbitrary types.

Import alias 'ads-js/comparators'

All comparators must implement the following common function interface:

/**
 * Compares elements a and b.
 *
 * @template T Type of compared elements.
 * @template K Optional type for element b used if comparator does support type conversion.
 * @param a Compared element.
 * @param b Compared element.
 * @returns Result of comparison (1 if a is greater than b, -1 if a is less than b, 0 if they are equal).
 */
export interface IComparator<T, K = T> {
  (a: T, b: K): ComparisonResult;
}

By default this library uses compareAsNumbers() everywhere if other not stated explicitly.

compareAsStrings()

/**
 * Compares the two elements a and b as Unicode strings. Both elements are allowed to be of any type.
 * Type conversion is done implicitly by the comparator.
 *
 * @param a Compared element.
 * @param b Compared element.
 * @returns Result of comparison (1 if a is greater than b, -1 if a is less than b, 0 if they are equal).
 */
function compareAsStrings<T, K>(a: T, b: K): ComparisonResult

compareAsNumbers()

/**
 * Compares the two elements a and b as float numbers. Both elements are allowed to be of any type besides NaN and
 * any other converted to number as NaN. Throws an error if any of the elements is NaN after the type conversion.
 *
 * @throws {ADSError} Can not compare with NaN.
 * @param a Compared element.
 * @param b Compared element.
 * @returns Result of comparison (1 if a is greater than b, -1 if a is less than b, 0 if they are equal).
 */
function compareAsNumbers<T, K>(a: T, b: K): ComparisonResult

Last updated

Was this helpful?