You are viewing a single thread.
View all comments View context
3 points

I think the main shortcoming here is that there isnt a way to specify the type to sort as, instead you have to write the function to compare them as numbers yourself. If it’s such a simple implementation, why isn’t it officially implemented? Why isn’t there a sortAs() that takes two args, the input list, and a Type value? Check every element matches the type and then sort, otherwise return a Type Error.

permalink
report
parent
reply
1 point
*

I mean, there’s a sort() method that takes a comparator(a,b) such that if a comes first it returns 1, if b comes first it returns -1 and if they’re equivalent wrt sortinf it returns 0. If you absolutely need type safe number sorting you can use that to get it.

permalink
report
parent
reply
2 points

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.

permalink
report
parent
reply
2 points

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.

permalink
report
parent
reply

Programmer Humor

!programmer_humor@programming.dev

Create post

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

  • Keep content in english
  • No advertisements
  • Posts must be related to programming or programmer topics

Community stats

  • 7K

    Monthly active users

  • 950

    Posts

  • 35K

    Comments