Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

hah, well then you can of course continue...

    return (cellA === cellB) ? 0 : (cellA > cellB ? 1 : -1);


Keep going:

    return (cellA > cellB) * 1 + (cellA < cellB) * -1;
More:

    return Math.sign(cellA - cellB);


You don't need the * 1 multiplication:

   return (cellA > cellB) - (cellA < cellB);


does work for NaN... rookie mistake, eh


Math.sign trick doesn't work for strings.


That's true, but the default string comparison sometimes isn't that useful, right? I somehow assumed the data is numbers only, rookie mistake :)

    'ana' > 'Bob'
    '2' > '123'
You usually want to clearly define the order or pre-process the strings in some way (trim them, same casing, etc).


Well, you can pass the strings through .toUpperCase() before comparing them.

Or indeed drop the <, > based approach and use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Or: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...


honestly? i like it. properly formatted it looks alright:

    return (
      (cellA === cellB) ? 0 :
      (cellA >   cellB) ? 1 :
      -1
    );
and it's an expression, so i immediately know it won't do any weird control flow. i'd prefer "if/then/else" vs "?/:" but it's not bad


This works fine if the ? operator is right-associative, but in PHP it's left-associative and you have a subtle bug.

I find a better indendation style for this is more like

    condition
        ? truthy
        : falsy


i use that style too sometimes, depends on what's clearer. IME the former usually works better if you have a multiple tests, but the latter is the only readable option if you need to break a case across lines.

yeah, ternary-if is busted in php :/ (far from the only thing that's busted there though...) i'm actually doing some PHP work right now, and never chain ifs to avoid this exact thing.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: