Idea for ECMAScript 7: Number.compare(a, b)
Claude Pache
claude.pache at gmail.com
Fri Jun 6 08:02:56 PDT 2014
Le 6 juin 2014 à 01:18, C. Scott Ananian <ecmascript at cscott.net> a écrit :
> On Thu, Jun 5, 2014 at 7:15 PM, Axel Rauschmayer <axel at rauschma.de> wrote:
>> ```js
>> // Compact ECMAScript 6 solution
>> // Risk: number overflow
>> [1, 5, 3, 12, 2].sort((a,b) => a-b)
>> ```
>
> Is this really an issue for IEEE floating point?
> --scott
Right. More precisely, if `a` and `b are both finite, but too far apart for `a - b` to be representable by a finite number,
we get either `a - b == Infinity > 0`, or `a - b == -Infinitiy < 0`, so that `a` and `b` are still correctly ordered.
There is a potential issue if some of the numbers you want to sort are infinite,
because you get, in some occasions, `a - b is NaN` where you need `a - b == 0`.
In that case, the behaviour of the sort function is explicitly left undefined by the current ES specification.
This could be simply resolved spec-wise by requiring to interpret the result of the compare function as `0` whenever it produces `NaN`.
For that case, I've filed:
https://bugs.ecmascript.org/show_bug.cgi?id=2978
(Naturally, if some of the numbers are `NaN`, you are out of luck.)
—Claude
More information about the es-discuss
mailing list