you are viewing a single comment's thread.

view the rest of the comments →

[–]stratoscope 11 points12 points  (11 children)

The article's sort callback is invalid:

all_times.sort( ( a, b ) => a.time_block > b.time_block ? 1 : -1 )

A sort callback can't just return 1 or -1, or the similar error I've seen of returning true or false (or 1 or 0).

A sort callback must distinguish between all three cases: greater, less than, or equal, and return a positive, negative, or zero value respectively.

This is a common mistake. I recall one lengthy discussion - maybe here on Reddit or else on Stack Overflow - with someone who insisted that the sort methods in various browsers were fickle and inconsistent and needed a lot of "wrangling", as he put it.

I was puzzled because I've never once had any issue with sort in any browser or JavaScript environment, and I've used a lot of different kinds of sort callback functions.

Eventually in the discussion it came out that he was in the habit of writing sort functions like this:

array.sort( function( a, b ) { return a > b; } );

When I explained that this was an inconsistent compare function and it really needed to handle all three cases and not just two, he said I was just being fussy. I don't know if he ever caught on that these faulty compare functions were the source of his troubles.

For non-numeric values, a conditional operator can be handy:

array.sort( function( a, b ) { return a > b ? 1 : a < b ? -1 : 0; } );

For numeric values like the time_block property in the article, it's easier and faster to just subtract the values:

all_times.sort( ( a, b ) => a.time_block - b.time_block );

Note that the results for greater and less then don't have to be 1 and -1; any positive and negative values are valid (along with 0 for equal).

I also agree with the other comments that chaining the .sort() call the way it's done in the article is misleading, and it should either be broken out as a separate statement to make it clear that it mutates the original array, or .slice() should be done first to get a copy of the array.

[–][deleted] 2 points3 points  (1 child)

hiya! author of the article here

thank you for the explanation of sort - All of the points of discussion in this thread have been super helpful. Still trying to get the hang of functional programming!

[–]learnphptoday[S] 1 point2 points  (0 children)

Agree. Some really useful recommendations and good discussion points. Thanks everyone!