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.