Comment on I'll just sort it myself
reverendsteveii@lemm.ee 1 year agoThink of digits like you would letters. You’re essentially sorting numbers alphabetically. It’s not the right way to do it, of course, but it’s the natural way to do it using a system like computers use that doesn’t necessarily differentiate between digits and letters unless you tell it to specifically.
CheezyWeezle@lemm.ee 1 year ago
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.
reverendsteveii@lemm.ee 1 year ago
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.
CheezyWeezle@lemm.ee 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.
reverendsteveii@lemm.ee 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.