-
-
Notifications
You must be signed in to change notification settings - Fork 369
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
consistent-existence-index-check
rule (#2425)
Co-authored-by: fisker <lionkay@gmail.com>
- Loading branch information
Showing
11 changed files
with
764 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
# Enforce consistent style for element existence checks with `indexOf()`, `lastIndexOf()`, `findIndex()`, and `findLastIndex()` | ||
|
||
💼 This rule is enabled in the ✅ `recommended` [config](https://github.com/sindresorhus/eslint-plugin-unicorn#preset-configs-eslintconfigjs). | ||
|
||
🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). | ||
|
||
<!-- end auto-generated rule header --> | ||
<!-- Do not manually modify this header. Run: `npm run fix:eslint-docs` --> | ||
|
||
Enforce consistent style for element existence checks with `indexOf()`, `lastIndexOf()`, `findIndex()`, and `findLastIndex()`. | ||
|
||
Prefer using `index === -1` to check if an element does not exist and `index !== -1` to check if an element does exist. | ||
|
||
Similar to the [`explicit-length-check`](explicit-length-check.md) rule. | ||
|
||
## Examples | ||
|
||
```js | ||
const index = foo.indexOf('bar'); | ||
|
||
// ❌ | ||
if (index < 0) {} | ||
|
||
// ✅ | ||
if (index === -1) {} | ||
``` | ||
|
||
```js | ||
const index = foo.indexOf('bar'); | ||
|
||
// ❌ | ||
if (index >= 0) {} | ||
|
||
// ✅ | ||
if (index !== -1) {} | ||
``` | ||
|
||
```js | ||
const index = foo.indexOf('bar'); | ||
|
||
// ❌ | ||
if (index > -1) {} | ||
|
||
// ✅ | ||
if (index !== -1) {} | ||
``` | ||
|
||
```js | ||
const index = foo.lastIndexOf('bar'); | ||
|
||
// ❌ | ||
if (index >= 0) {} | ||
|
||
// ✅ | ||
if (index !== -1) {} | ||
``` | ||
|
||
```js | ||
const index = array.findIndex(element => element > 10); | ||
|
||
// ❌ | ||
if (index < 0) {} | ||
|
||
// ✅ | ||
if (index === -1) {} | ||
``` | ||
|
||
```js | ||
const index = array.findLastIndex(element => element > 10); | ||
|
||
// ❌ | ||
if (index < 0) {} | ||
|
||
// ✅ | ||
if (index === -1) {} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
'use strict'; | ||
|
||
const {isNumberLiteral} = require('./literal.js'); | ||
|
||
function isNegativeOne(node) { | ||
return node?.type === 'UnaryExpression' | ||
&& node.operator === '-' | ||
&& isNumberLiteral(node.argument) | ||
&& node.argument.value === 1; | ||
} | ||
|
||
module.exports = isNegativeOne; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
'use strict'; | ||
const toLocation = require('./utils/to-location.js'); | ||
const {isMethodCall, isNegativeOne, isNumberLiteral} = require('./ast/index.js'); | ||
|
||
const MESSAGE_ID = 'consistent-existence-index-check'; | ||
const messages = { | ||
[MESSAGE_ID]: 'Prefer `{{replacementOperator}} {{replacementValue}}` over `{{originalOperator}} {{originalValue}}` to check {{existenceOrNonExistence}}.', | ||
}; | ||
|
||
const isZero = node => isNumberLiteral(node) && node.value === 0; | ||
|
||
/** | ||
@param {parent: import('estree').BinaryExpression} binaryExpression | ||
@returns {{ | ||
replacementOperator: string, | ||
replacementValue: string, | ||
originalOperator: string, | ||
originalValue: string, | ||
} | undefined} | ||
*/ | ||
function getReplacement(binaryExpression) { | ||
const {operator, right} = binaryExpression; | ||
|
||
if (operator === '<' && isZero(right)) { | ||
return { | ||
replacementOperator: '===', | ||
replacementValue: '-1', | ||
originalOperator: operator, | ||
originalValue: '0', | ||
}; | ||
} | ||
|
||
if (operator === '>' && isNegativeOne(right)) { | ||
return { | ||
replacementOperator: '!==', | ||
replacementValue: '-1', | ||
originalOperator: operator, | ||
originalValue: '-1', | ||
}; | ||
} | ||
|
||
if (operator === '>=' && isZero(right)) { | ||
return { | ||
replacementOperator: '!==', | ||
replacementValue: '-1', | ||
originalOperator: operator, | ||
originalValue: '0', | ||
}; | ||
} | ||
} | ||
|
||
/** @param {import('eslint').Rule.RuleContext} context */ | ||
const create = context => ({ | ||
/** @param {import('estree').VariableDeclarator} variableDeclarator */ | ||
* VariableDeclarator(variableDeclarator) { | ||
if (!( | ||
variableDeclarator.parent.type === 'VariableDeclaration' | ||
&& variableDeclarator.parent.kind === 'const' | ||
&& variableDeclarator.id.type === 'Identifier' | ||
&& isMethodCall(variableDeclarator.init, {methods: ['indexOf', 'lastIndexOf', 'findIndex', 'findLastIndex']}) | ||
)) { | ||
return; | ||
} | ||
|
||
const variableIdentifier = variableDeclarator.id; | ||
const variables = context.sourceCode.getDeclaredVariables(variableDeclarator); | ||
const [variable] = variables; | ||
|
||
// Just for safety | ||
if ( | ||
variables.length !== 1 | ||
|| variable.identifiers.length !== 1 | ||
|| variable.identifiers[0] !== variableIdentifier | ||
) { | ||
return; | ||
} | ||
|
||
for (const {identifier} of variable.references) { | ||
/** @type {{parent: import('estree').BinaryExpression}} */ | ||
const binaryExpression = identifier.parent; | ||
|
||
if (binaryExpression.type !== 'BinaryExpression' || binaryExpression.left !== identifier) { | ||
continue; | ||
} | ||
|
||
const replacement = getReplacement(binaryExpression); | ||
|
||
if (!replacement) { | ||
return; | ||
} | ||
|
||
const {left, operator, right} = binaryExpression; | ||
const {sourceCode} = context; | ||
|
||
const operatorToken = sourceCode.getTokenAfter( | ||
left, | ||
token => token.type === 'Punctuator' && token.value === operator, | ||
); | ||
|
||
yield { | ||
node: binaryExpression, | ||
loc: toLocation([operatorToken.range[0], right.range[1]], sourceCode), | ||
messageId: MESSAGE_ID, | ||
data: { | ||
...replacement, | ||
existenceOrNonExistence: `${replacement.replacementOperator === '===' ? 'non-' : ''}existence`, | ||
}, | ||
* fix(fixer) { | ||
yield fixer.replaceText(operatorToken, replacement.replacementOperator); | ||
|
||
if (replacement.replacementValue !== replacement.originalValue) { | ||
yield fixer.replaceText(right, replacement.replacementValue); | ||
} | ||
}, | ||
}; | ||
} | ||
}, | ||
}); | ||
|
||
/** @type {import('eslint').Rule.RuleModule} */ | ||
module.exports = { | ||
create, | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: | ||
'Enforce consistent style for element existence checks with `indexOf()`, `lastIndexOf()`, `findIndex()`, and `findLastIndex()`.', | ||
recommended: true, | ||
}, | ||
fixable: 'code', | ||
messages, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.