eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: `consistent-non-exists-index-check`

Open fisker opened this issue 4 years ago • 6 comments

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.

fisker avatar Jan 15 '21 10:01 fisker

Array#includes would be better for this, which we already have a rule for, so I'm not sure the point of this rule?

sindresorhus avatar Jan 16 '21 09:01 sindresorhus

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

fisker avatar Jan 16 '21 12:01 fisker

Ok. This rule makes sense then. We should make what you said above clear in the rule docs though.

sindresorhus avatar Jan 16 '21 14:01 sindresorhus

This is now accepted.

sindresorhus avatar Jan 27 '21 13:01 sindresorhus

Maybe, should if (foo.indexOf('bar') < 0) {} also be checked?

axetroy avatar Aug 19 '24 06:08 axetroy

Maybe, should if (foo.indexOf('bar') < 0) {} also be checked?

No point, since it's already caught by prefer-includes.

sindresorhus avatar Aug 19 '24 14:08 sindresorhus