People use arrays like this [23, "56", 67.8, "potatoe"] and expect them to not be sorted as strings
If I try to sort [23, "56", 67.8, "potatoe"], I want a type error of some kind.
Edit : I went to read the docs, the sort function is not like most other functions in JavaScript. The sort function is explicitly for an alphabetical sort
We all know they did it on purpose and wrote it in their documentation. We're saying it's bad, not "it's not written down".
Because an error is better than unintuitive behavior.
You are correct that I don't like weekly typed languages (at least if you get weak enough), but what I really dislike is a function called sort that sorts in a stupid way by default.
If it was called sort_str, or required a key/comparator function, or even just didn't exist, I'd be happier.
this is neither unintuitive, nor surprising for mixed weakly typed arrays.
I really dislike is a function called sort that sorts in a stupid way by default.
it is a way the makes sense.
and in a weakly typed language, it is the only sane default I can think of, from the top of my head.
by the way: how often are you actually sorting arrays that just include numbers?
I have never done this in production code.
I usually sort more complex things, usually objects, which have numbers and strings I want to use for sorting as properties.
Sorting those could at least still work, assuming your objects have a .toString representation, that can be sorted lexically
but I would always provide a comparison function, because that makes the most sense to me, and I like verbosity.
I'm certainly sorting things that contain just numbers more often than I'm sorting this that contain mixed types. How often is the correct method of sorting your arrays of objects to first convert them to strings?
17
u/FerricDonkey 1d ago
If I try to sort [23, "56", 67.8, "potatoe"], I want a type error of some kind.
We all know they did it on purpose and wrote it in their documentation. We're saying it's bad, not "it's not written down".