Idea for ECMAScript 7: Number.compare(a, b)

# Axel Rauschmayer (11 years ago)

It’d be nice to have a built-in way for comparing numbers, e.g. when sorting arrays.

// Compact ECMAScript 6 solution
// Risk: number overflow
[1, 5, 3, 12, 2].sort((a,b) => a-b)

// Proposed new function:
[1, 5, 3, 12, 2].sort(Number.compare)
# C. Scott Ananian (11 years ago)

On Thu, Jun 5, 2014 at 7:15 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

// 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?

# Mathias Bynens (11 years ago)

On 6 Jun 2014, at 01:15, Axel Rauschmayer <axel at rauschma.de> wrote:

It’d be nice to have a built-in way for comparing numbers, e.g. when sorting arrays.

// Compact ECMAScript 6 solution
// Risk: number overflow
[1, 5, 3, 12, 2].sort((a,b) => a-b)

// Proposed new function:
[1, 5, 3, 12, 2].sort(Number.compare)

That sorts in ascending order. What if you need to sort in descending order? Would there need to be a built-in function for that too?

# Hemanth H.M (11 years ago)

Something like:

Number.compare = (n1, n2) -> (n1 - n2) / Math.abs(n1 - n2) || 0;
# Hemanth H.M (11 years ago)

My bad! Miss read it. ^That still sorts in ascending order only.

# Claude Pache (11 years ago)

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:

// 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 fora - bto be representable by a finite number, we get eithera - b == Infinity > 0, ora - b == -Infinitiy < 0, so thataandb` 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: ecmascript#2978

(Naturally, if some of the numbers are NaN, you are out of luck.)