Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [prefer-includes] ignore option chaining before indexOfs #3432

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/eslint-plugin/docs/rules/prefer-includes.md
Expand Up @@ -60,6 +60,10 @@ userDefined.includes(value);

// the two methods have different parameters.
mismatchExample.indexOf(value) >= 0;

// ?. optional chaining changes the logic flow
let maybe: string;
maybe?.indexOf('');
```

## Options
Expand Down
17 changes: 6 additions & 11 deletions packages/eslint-plugin/src/rules/prefer-includes.ts
Expand Up @@ -126,18 +126,13 @@ export default createRule({
}

return {
[[
// a.indexOf(b) !== 1
"BinaryExpression > CallExpression.left > MemberExpression.callee[property.name='indexOf'][computed=false]",
// a?.indexOf(b) !== 1
"BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name='indexOf'][computed=false]",
].join(', ')](node: TSESTree.MemberExpression): void {
// a.indexOf(b) !== 1
"BinaryExpression > CallExpression.left > MemberExpression.callee[property.name='indexOf'][computed=false]"(
node: TSESTree.MemberExpression,
): void {
// Check if the comparison is equivalent to `includes()`.
const callNode = node.parent as TSESTree.CallExpression;
const compareNode = (callNode.parent?.type ===
AST_NODE_TYPES.ChainExpression
? callNode.parent.parent
: callNode.parent) as TSESTree.BinaryExpression;
const compareNode = callNode.parent as TSESTree.BinaryExpression;
const negative = isNegativeCheck(compareNode);
if (!negative && !isPositiveCheck(compareNode)) {
return;
Expand Down Expand Up @@ -229,7 +224,7 @@ export default createRule({
}
yield fixer.insertTextAfter(
argNode,
`${node.optional ? '?.' : '.'}includes(${JSON.stringify(text)}`,
`${node.optional ? '?.' : '.'}includes('${text}'`,
);
},
});
Expand Down