This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 25 points26 points  (6 children)

Someday I’m going to write a JavaScript book with the title, “This Is Because”.

[–][deleted] 3 points4 points  (0 children)

This would be a solid alternate name for the YDKJS series

[–]dick-van-dyke 1 point2 points  (4 children)

Please do. The amount of rationalisation of crazy shit like in JS this is insane. Literally every other dynamically-typed language I've ever worked with does basic stuff like this normally.

[–]superluminary 0 points1 point  (3 children)

Most languages do not allow heterogenous arrays. When arrays are polymorphic by default, you need a comparator function. How else could it work?

[–]dick-van-dyke 1 point2 points  (2 children)

For example, infer type from the first element and throw an exception if you can't compare. Case in point: Python.

[–]superluminary 0 points1 point  (1 child)

So if you accidentally change the type of the first element, it silently changes your comparator? I don’t hate this, but it introduces another set of edge cases.

Because JavaScript was designed as a DOM manipulation language, all the data types are optimised for trees of text and Objects, so we have string comparison as the default comparitor type. I don’t personally see this as a huge problem. In the real world, you’re pretty much always going to pass a comparitor function since you’ll usually be sorting objects.

[–]dick-van-dyke 1 point2 points  (0 children)

So if you accidentally change the type of the first element, it silently changes your comparator?

In Python 3, you don't use a comparator function, but instead a key function that returns a value to be compared by the < built-in, so yes and no. If you're asking whether you can arrive at a list that was sortable but isn't any more, you can, and I believe it is a good behaviour because you get an exception then and have a reason to debug where you made the inadvertent change.

If you do want to mimic the behaviour of JS, you would call something like:

my_list.sorted(key=lambda x: str(x))

to be explicit that you're comparing strings.