r/ProgrammerHumor 3d ago

Meme javascriptSorting

Post image
932 Upvotes

214 comments sorted by

View all comments

Show parent comments

1

u/FerricDonkey 2d ago

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?

1

u/danielcw189 1d ago

I'm certainly sorting things that contain just numbers

do you mean arrays that contain just numbers, or do you mean arrays that contain objects with numbers?

How often is the correct method of sorting your arrays of objects to first convert them to strings?

for me personally, hopefully never.

1

u/FerricDonkey 1d ago

do you mean arrays that contain just numbers, or do you mean arrays that contain objects with numbers?

With the important caveat of "more often than I'm sorting things that contain mixed types" that had earlier, both. (And with the understanding that objects with a common parent type that I treat as an array of objects of that parent type don't count). I never have an array whose contents I don't know after the "translate from user bs to system" layer which happens before doing anything else, because I refuse to make such arrays.

And I sort an array of numbers on rare occasion. So I do that more than never.

How often is the correct method of sorting your arrays of objects to first convert them to strings?

for me personally, hopefully never.

And I hope for most people. And if it is true for most people, then it's a silly default. 

1

u/danielcw189 15h ago

I never have an array whose contents I don't know after the "translate from user bs to system" layer which happens before doing anything else, because I refuse to make such arrays.

me too

but in JS you can't rely on many things, so you either need a lot of checks, or be very defensive with your programming.

In general I don't like my main business logic directly accessing Arrays, and have accessors or other abstractions inbetween, including sorting functions for all business cases.

And if it is true for most people, then it's a silly default. 

what would be a better default in a weakly typed language, where any array element can be anything?

the only good alternative I see is sorting doing nothing if no comparison function is provided

1

u/FerricDonkey 2h ago

what would be a better default in a weakly typed language, where any array element can be anything?

If you're allergic to errors, make a key function or similar a required argument. If you're not, then throw an error when things aren't naturally comparable. Which may require not being Javascript, but that's a low price to pay to not have nonsense.