# Comparator function in Javascript [closed]

Need to write a JS function compare(a,b) for numbers which return 1 when a > b, 0 when a == b, -1 when a < b. Also following properties should hold:

1. compare(NaN, NaN) = 0
2. NaN is bigger than any other number, so compare(NaN, any) = 1 and compare(any, NaN) = -1.
3. compare(-0.0, 0.0) = -1 and compare(0.0, -0.0) = 1. Other numbers are ordered by default.

Other way to define: function should behave as Double.compare method in Java.

• sounds like Implement the <=> three-way comparison operator on numbers but floating-point only. Commented Sep 19, 2023 at 8:42
• @SuperStormer As far as I can tell the other challenge does not require handling of non-finite numbers which seems to be the main part of this challenge Commented Sep 19, 2023 at 8:58
• Welcome to Code Golf. As it stands, this challenge is lacking an objective winning criterion. If this is actually a programming question, it is off-topic on this site and may be better received on Stack Overflow. Commented Sep 19, 2023 at 9:02
• Include a code-golf tag if you are seeking for golfing answers. Or you may be get help on Stack Overflow if you are asking general programming questions.
– tsh
Commented Sep 19, 2023 at 10:58
• JavaScript (Node.js), 53 bytes: compare=(a,b)=>Math.sign(a-b||1/a-1/b||(b==b)-(a==a))
– l4m2
Commented Sep 20, 2023 at 15:49

# JavaScript (Node.js), 61 bytes

-5 bytes, thanks to l4m2

compare=(a,b)=>(a>b)-(b>a)||(1/a>1/b)-(1/b>1/a)+(b==b)-(a==a)


Attempt This Online!

## Explanation

compare=(a,b)=>
(a>b)-(b>a)||        // compare values, return if non-zero
(1/a>1/b)-(1/b>1/a)  // compare inverse values to check for -0<0
+(b==b)-(a==a)      // compare equalities to check for NaN

• ?x: ==> ||.
– l4m2
Commented Sep 20, 2023 at 15:38