abab, asc, 123, abc
ㄹ @disjukr@hackers.pub
TL;DR
arr.sort((a, b) => a - b); is not as good as sortAsc(arr),
and sortAsc(arr) is not as good as sort123(arr) or sortAbc(arr).
When I encounter code like this:
arr.sort((a, b) => a - b);
I usually open the JavaScript console and run:
[3, 2, 1].sort((a, b) => a - b); // [1, 2, 3]
to verify whether it's ascending or descending order.
Although it's a pattern I encounter frequently, and I can immediately recognize "abab" as ascending order, I still double-check every time to make sure I'm reading it correctly.
// Sort arr in ascending order
arr.sort((a, b) => a - b);
Adding a comment like this to indicate whether it's ascending or descending is somewhat better, but I have low expectations for people.
// Sort arr in ascending order
arr.sort((a, b) => b - a); // ?
How would you know if someone changed the original ascending sort to descending but didn't update the comment?
I've encountered countless instances (even today) where someone modified code but didn't update the comments or documentation.
For cases like this, it's better to create a function with a name that clearly describes its behavior rather than relying on comments.
// In real code, having it named "sort asc" would be considerate.
// Most people name functions something like sortBlablaArr
// without mentioning whether it's ascending, descending, or using some third criterion.
function sortAsc(arr) {
return [...arr].sort((a, b) => a - b);
}
However, when I see the name sortAsc, it doesn't immediately click for me, and I go through roughly this mental process:
- Expand it to "sort ascending"
- Translate to "ascending sort" in my language
- Realize it means sorting in increasing (rising) order
- So it will be like
1,2,3
At this point, for me, interpreting sortAsc(arr) takes about as much mental effort as arr.sort((a, b) => a - b).
The advantage of sortAsc(arr) is that I can interpret it without opening the JavaScript console.
That's why I wish people would use names like sort123 for ascending sorts and sort321 for descending sorts.
Compared to the other code examples mentioned earlier, something like sort123(arr) can significantly reduce the mental interpretation steps in my head.
If using "sort" as a prefix feels unnatural (due to redundancy or other reasons), and using just 123 or 321 is problematic because identifiers can't start with numbers, I suggest alternatives like abc and cba (i.e., sortAbc(arr), sortCba(arr)).