More sort comparison functions

Temporal's going to have a Temporal.Absolute.compare function suitable for Array.prototype.sort. By any chance, can we have some more comparison functions for existing data types, for similar uses?

  • Number.compare
  • BigInt.compare
  • String.compare (useful when sorting an array of objects by a string key)
  • Date.compare

Code for each of those would be pretty obvious:

// Note: this considers `NaN`s as equal on purpose
Number.compare = (a, b) => {
    a = +a; b = +b
    if (a > b) return 1
    if (a < b) return -1
    return 0
}

BigInt.compare = (a, b) => {
    a = BigInt(a); b = BigInt(b)
    if (a > b) return 1
    if (a < b) return -1
    return 0
}

String.compare = (a, b) => {
    a = "" + a; b = "" + b
    if (a > b) return 1
    if (a < b) return -1
    return 0
}

Date.compare = (a, b) => {
    if (!(a instanceof Date && b instanceof Date)) throw new TypeError()
    return Number.compare(a.getTime(), b.getTime())
}

Also, each of those could be very easily optimized for by the engine, as they already have to do 99% of that just for a single > or < check, and they could just reduce it to effectively that kind of cost.

4 Likes

This all looks handy and would help eliminate boilerplate code. How about a case-insensitive String.compare as well?

There is already Intl.Collator for that case.

1 Like

And to add onto that, strings.sort((a, b) => a.localeCompare(b)) is equivalent to strings.sort(new Intl.Collator().compare), just slightly less efficient.

Case-insensitive comparisons can't really be done in a language-independent manner, and my String.compare is just lexicographic and based on character code order. It's not actually useful for language in general, and as .sort does that by default, it's not useful there. However, it's useful for things like binary search of a sorted list of strings or other similar low-level locale-independent string tasks.