I cam across this use case and I am puzzled by it :
const naturalCollator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
});
const comparator = (a, b) => naturalCollator.compare(a, b);
const numbers = [-1, 0, 1, 10, NaN, 2, -0.001, NaN, 0, -1, -Infinity, NaN, 5, -10, Infinity, 0];
console.log(numbers.sort(comparator));
The result array list negative numbers in descending order, while positive in ascending order. For example :
[-3, 1, -2, 2].sort(comparator)
// [-2, -3, 1, 2]
Since Intl.Collator is a "language-sensitive string comparison", does it simply ignore the sign and only evaluates every number as positive?
Edit
Another inconsistency is this one:
["b1", "a-1", "b-1", "a+1", "a1"].sort(comparator);
// ['a-1', 'a+1', 'a1', 'b-1', 'b1']
Where 'a' < 'b'
so the order is OK, but '-' > '+'
so why is "a-1"
before "a+1"
?
In other words, a negative sign is considered less than a positive sign regardless of it's character code, however "-1"
is considered less than "-2"
, ignoring the sign.