-4
\$\begingroup\$

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.

\$\endgroup\$
8
  • \$\begingroup\$ sounds like Implement the `<=>` three-way comparison operator on numbers but floating-point only. \$\endgroup\$ Commented Sep 19, 2023 at 8:42
  • \$\begingroup\$ @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 \$\endgroup\$
    – bsoelch
    Commented Sep 19, 2023 at 8:58
  • 7
    \$\begingroup\$ 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. \$\endgroup\$
    – Arnauld
    Commented Sep 19, 2023 at 9:02
  • \$\begingroup\$ 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. \$\endgroup\$
    – tsh
    Commented Sep 19, 2023 at 10:58
  • \$\begingroup\$ JavaScript (Node.js), 53 bytes: compare=(a,b)=>Math.sign(a-b||1/a-1/b||(b==b)-(a==a)) \$\endgroup\$
    – l4m2
    Commented Sep 20, 2023 at 15:49

1 Answer 1

-1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ ?x: ==> ||. \$\endgroup\$
    – l4m2
    Commented Sep 20, 2023 at 15:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.