• CheezyWeezle@lemm.ee
    link
    fedilink
    arrow-up
    1
    ·
    1 year ago

    Right, but you have to make that comparator yourself, it’s not a built-in part of the language. The only built-in comparator converts values to strings and compares them in code units orders.

    Also, that technically isnt type-safe, is it? If you threw a string or a NaN at that it would fail. As far as I knew, type safe means that a function can handle type errors itself, rather than throwing an exception. So in this case the function would automatically convert types if it was type-safe to prevent an unhandled exception.

    • Alien Nathan Edward@lemm.ee
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Not every use case can be the built-in default. I wouldn’t have made JS weakly typed if I were designing it, but once the decision was made to use weak typing it made sense to either have no default sort method or to have a default sort method that assumes a type.

      What I’ve outlined for you is the interface for a comparator, not the implementation. You can type check and convert and do anything else you want under the hood of the comparator you write.

      • CheezyWeezle@lemm.ee
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        It doesn’t have to be the default to be built in, tho. It could be an overloaded function, having the “default” be the typical convert-to-string sorting, and an overloaded function that allows to specify a type.

        It’s just such a common thing, wanting to sort a list by different types, that I’m surprised there hasn’t been an official implementation added like this. I get that it a simple “fix” to make, but I just think that if it’s that simple yet kind of obscure (enough that people are still constantly asking about it) there should be an official implementation, rather than something you have build yourself.

        • Alien Nathan Edward@lemm.ee
          link
          fedilink
          arrow-up
          1
          ·
          1 year ago

          Thats just JS for you. If you’re being generous, it’s a “quirky” language. If you’re being ungenerous, it’s a steaming pile of arbitrary decisions, gotchas, unexpected behaviors and problems that no one bothered to solve because there’s a workaround.