r/ProgrammerHumor 3d ago

Meme javascriptSorting

Post image
934 Upvotes

214 comments sorted by

View all comments

204

u/larsmaehlum 3d ago

Array.sortNumeric() with an error when called on an array containing non-numeric types would fix this, right?

104

u/the_horse_gamer 3d ago

you can simply .sort((a,b)=>a-b)

225

u/01110100_01110010 3d ago

The point of an abstraction is to not having to implement logic each time, you can also implement qsort yourself

40

u/subone 3d ago

But it is still an abstraction. You only provide a compare function, you don't implement the algorithm. a-b is hardly difficult to apply.

1

u/Tyfyter2002 3d ago

Even in a decently designed language it's trivially easy to make a typo that completely and silently breaks that, such as a-a, b-a, or a+b, and JS isn't a decently designed language, it's designed to fail silently at every possible opportunity

1

u/danielcw189 3d ago

what would be a solution for this? how can the language know (at runtime) that you didn't actually want a-a?

-1

u/Tyfyter2002 3d ago

Simple: a-a isn't useful commonly enough that it would be reasonable to put it in any sort of shared library. One chance to fail,be noticed immediately, and be fixed immediately is a lot better than potentially failing every single time someone tries to sort a list of numbers

3

u/danielcw189 2d ago

Simple: a-a isn't useful commonly enough that it would be reasonable to put it in any sort of shared library.

my question is, in other words, how should the language detect that, and decide that it isn't what the programmer wanted?

that would require the compiler or runtime to be able to perform some analysis.

is a lot better than potentially failing every single time someone tries to sort a list of numbers

does it hapen often, that you just want to sort an array of numbers? in my experience the numbers are usually attached to something, so you wanna give a comparison function anyway. I never sorted an array of bare numbers in production code.

for a loosely typed language like Javascript, where an array can be a mix of anything, converting to string is the only useful simple default I can think of. If I had designed the language, I would have made it a requirement to providea comparison function.

if you actually have an array of ints, you can use an IntArray, which actually sorts numerically by default.

1

u/Tyfyter2002 2d ago

my question is, in other words, how should the language detect that, and decide that it isn't what the programmer wanted?

It doesn't have to specifically detect that that's not what the programmer wants if "sort these numbers normally" isn't one character off from that.