Comparators
Comparators turn any comparing function into a sorting function, without fretting browser inconsistencies. (5 min. read)
We'll cover the following...
Ascend and Descend
You won’t need these as often as the main sorting functions, but they can be useful in some scenarios.
The functions we just saw, ascend/descend, are comparators. They take a function to apply against each value.
Here’s a sort by height.
Ramda’s prop function can replace the getHeight function.
Descend sorts in the opposite direction, greatest first.
And path lets you easily compare things, no matter how nested their properties are.
Lower-Level Comparator
Ramda also has a comparator function. It creates comparator functions out of regular functions that compare two elements.
This function, for example…
…works with sort in modern browsers.
But since byHeight returns a boolean, older browsers like Internet Explorer won’t sort people correctly. Older browsers require your comparator to return a number!
See this StackOverflow answer for more details.
A proper comparator looks like this
Allowing this sort to work everywhere.
A bit verbose. Fortunately, Ramda turns any comparison function into a proper comparator. All we need is the comparator function.
Take your original byHeight function and flip > to <…
And wrap it in comparator. I’d prefer renaming it so the comparator function can be named byHeight.
Now use it.