eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: `consistent-non-exists-index-check`
Similar to explicit-length-check, enforce consistent style when check index === -1 or index !== -1
Fail
const index = foo.indexOf('bar');
if (index < 0) {}
const index = foo.indexOf('bar');
if (index >= 0) {}
Pass
const index = foo.indexOf('bar');
if (index === -1) {}
const index = foo.indexOf('bar');
if (index !== -1) {}
But this is hard to detect, since we already enforce includes if indexOf() is in a position as boolean.
Array#includes would be better for this, which we already have a rule for, so I'm not sure the point of this rule?
Sometime, we want index, but need check if it's -1 before using it, example https://github.com/sindresorhus/eslint-plugin-unicorn/blob/5ba0f8379d06e581c614245200bdbd3d935822a7/rules/no-array-push-push.js#L40-L44
Ok. This rule makes sense then. We should make what you said above clear in the rule docs though.
This is now accepted.
Maybe, should if (foo.indexOf('bar') < 0) {} also be checked?
Maybe, should if (foo.indexOf('bar') < 0) {} also be checked?
No point, since it's already caught by prefer-includes.