Comp 110 Comparator Interface and A_BEFORE/SAME_AS/AFTER_B

The Comparator Interface

The Comparator interface has a signature that looks like:

interface Comparator<T> {
    (a: U, b: T): number;
}

A function of type 'Comparator' takes in two numbers (an 'a' and a 'b'), returning:

  • a negative number when a comes before b (-1)
  • a positive number when a comes after b (+1)
  • zero when a is the same as b and their order doesn't matter

Comparators are often used in sorting algorithms, described here

A_BEFORE/SAME_AS/AFTER_B

Rather than memorizing these 'magic numbers' - we use "constants" that store these values instead!

  • A_BEFORE_B is a number whose value is -1
  • A_SAME_AS_B is a number whose value is 0
  • A_AFTER_B is a number whose value is 1

By importing this interface and these constants, we have access to them in our code!