strict-array-sort
The problem
Many developers don't look up
documentation quite enough, and sometimes
think that comparator function in Array.sort
should return boolean and implement
sorting like this:
[1,3,2,4,5].sort((a,b)=>a>b);
returns
[ 1, 2, 3, 4, 5 ]
Sometimes it even works if you are lucky. But comparator function should return positive number, negative number or zero, otherwise sorting is broken:
5 8 7 1 2 3 4 6 9 10 11 12 13
returns
[ 4, 5, 3, 1, 2, 6, 7, 8, 9, 10, 11, 12, 13 ]
Also, there were changes in sorting in V8, and using booleans in comparators is broken even more than it was before.
13245;
[ 1, 3, 2, 4, 5 ]
Solution
Of cause, you will have to fix your code. But to fix something, you need to find it at first, yeah? And sometimes you have a really large codebase to search in. That's when this module will help you. It has two modes:
Strict mode
All code which returns non numeric values from comparators will start throwing errors. To enable it, just install the module and initialize it like this:
const strictSort = ;strictSort;
Soft mode
If you don't want to throw errors, and want to just write logs, you can do it too:
const strictSort = ;strictSort ;
Warning
This module overrides Array.sort
prototype to add check for comparator.
It is pretty dangerous and probably should not be used in production code.