Using the sort
method without a comparator argument will coerce all elements in the array to strings and lexigraphically organize them. When sorting an array of numbers or objects, it is advised to provide a comparator function; this plugin enforces that rule.
Examples of incorrect code for this rule:
const sorted = [1, 10, 11, 100].sort(); // [1, 10, 100, 11]
Examples of correct code for this rule:
const sorted = [1, 10, 100, 11].sort(function (a, b) {
return a - b;
}); // [1, 10, 11, 100]
This module is distributed via npm which is bundled with node and
should be installed as one of your project's devDependencies
:
npm install --save-dev eslint-plugin-explicit-comparator
This library has a required peerDependencies
listing for eslint
.
Add explicit-comparator
to the plugins section of your .eslintrc
configuration file.
You can omit the eslint-plugin-
prefix:
{
"plugins": ["explicit-comparator"]
}
Then configure the rules you want to use under the rules section.
{
"rules": {
"explicit-comparator/explicit-comparator": "warn"
}
}
MIT