Skip to content

Comparators

MatApple edited this page Aug 25, 2015 · 7 revisions

Immutable uses comparator functions for a few methods including sort, max, and min. Comparators are also used in JavaScript's Array#sort method.

Comparators have the signature, <V>(valueA: V, valueB: V): number

  • Returns 0 if the elements are equivalent.
  • Returns 1 (or any positive number) if valueA is greater than valueB.
  • Returns -1 (or any negative number) if valueB is greater than valueA.
  • Is pure, i.e. it must always return the same value for the same pair of values.

The default comparator:

function defaultComparator(a, b) {
  return a > b ? 1 : b > a ? -1 : 0;
}

A common pitfall when using comparators is accidentally providing a function which returns a boolean rather than a number. true and false will coerce to 1 and 0 respectively, failing to distinguish between valueA being less than valueB or the two being equal.

A useful utility for converting a boolean function (predicate) which describes if a is greater than b to a comparator, note the similarity to the defaultComparator:

function comparatorFromPredicate(pred) {
  return function (a, b) {
    return pred(a, b) ? 1 : pred(b, a) ? -1 : 0
  };
}