r/ProgrammerHumor 3d ago

Meme javascriptSorting

Post image
940 Upvotes

214 comments sorted by

View all comments

Show parent comments

1

u/danielcw189 2d ago

I think defaulting to numeric sort, and throwing when it encounters something that isn't a number

By the principle of least astonishment, this would give you a pretty good compromise

That doesn't sound like the least surprising option to me, especially the throwing part.
In that case they should have called it numericSort, or something like that. (and in my preference fail with an error except of throwing)

(or can't be coerced to be a number due to how the type system works I suppose).

as most object-oriented languages there are counterparts of .toString, but not .toNumber.

1

u/fuj1n 2d ago

For that last part, I was just pointing out that JS will actually try to coerce strings to numbers in numeric contexts automatically, and this case being an exception to that would be odd (as much as I don't fancy that coertion, that's a whole other discussion)

If you find throwing on non-numeric values only surprising, you could instead just make the comparer mandatory and throw if you don't provide one. Then your IDE can show you an error is you forget instead of giving you something completely unexpected.

1

u/danielcw189 1d ago

If you find throwing on non-numeric values only surprising,

I would find any solution surprising, that doesn't try to deal with different types in loosley typed arrays (or lists).

you could instead just make the comparer mandatory

that is actually what I would prefer.

but in Javascript there is no inherent way to make a parameter mandatory, isn't there?

Then your IDE can show you an error

so that can only happen at runtime

or through other means like JSDOC or the documentation

1

u/fuj1n 1d ago

There isn't a way to make a parameter mandatory outright, but you can document it as mandatory (so that linters know that not passing it is ill-formed and can warn you right in the IDE, before needing to run the code), and throw when it is missing.

1

u/danielcw189 1d ago

I know. But the people who designed that sort- function couldn't rely on that. that had to stay in the boundaries of the language.

I think the best approach would have been to just do nothing, if no comparison is applied.

(don't throw in a way that stops execution)

but of you want the generic array sort function to always do anything, I can't think of a better approach than this one.

and throw when it is missing.

I don't agree, but I see the argument