Skip to content

feat(eslint-plugin): add rule prefer-find #8216

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

Merged
merged 15 commits into from
Feb 3, 2024
39 changes: 39 additions & 0 deletions packages/eslint-plugin/docs/rules/prefer-find.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
description: 'Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.'
---

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/prefer-find** for documentation.

When searching for the first item in an array matching a condition, it may be tempting to use code like `arr.filter(x => x > 0)[0]`.
However, it is simpler to use [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) instead, `arr.find(x => x > 0)`, which also returns the first entry matching a condition.
Because the `.find()` only needs to execute the callback until it finds a match, it's also more efficient.

:::info

Beware the difference in short-circuiting behavior between the approaches.
`.find()` will only execute the callback on array elements until it finds a match, whereas `.filter()` executes the callback for all array elements.
Therefore, when fixing errors from this rule, be sure that your `.filter()` callbacks do not have side effects.

:::

<!--tabs-->

### ❌ Incorrect

```ts
[1, 2, 3].filter(x => x > 1)[0];

[1, 2, 3].filter(x => x > 1).at(0);
```

### ✅ Correct

```ts
[1, 2, 3].find(x => x > 1);
```

## When Not To Use It

If you intentionally use patterns like `.filter(callback)[0]` to execute side effects in `callback` on all array elements, you will want to avoid this rule.
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ export = {
'prefer-destructuring': 'off',
'@typescript-eslint/prefer-destructuring': 'error',
'@typescript-eslint/prefer-enum-initializers': 'error',
'@typescript-eslint/prefer-find': 'error',
'@typescript-eslint/prefer-for-of': 'error',
'@typescript-eslint/prefer-function-type': 'error',
'@typescript-eslint/prefer-includes': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/disable-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export = {
'@typescript-eslint/no-useless-template-literals': 'off',
'@typescript-eslint/non-nullable-type-assertion-style': 'off',
'@typescript-eslint/prefer-destructuring': 'off',
'@typescript-eslint/prefer-find': 'off',
'@typescript-eslint/prefer-includes': 'off',
'@typescript-eslint/prefer-nullish-coalescing': 'off',
'@typescript-eslint/prefer-optional-chain': 'off',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ import parameterProperties from './parameter-properties';
import preferAsConst from './prefer-as-const';
import preferDestructuring from './prefer-destructuring';
import preferEnumInitializers from './prefer-enum-initializers';
import preferFind from './prefer-find';
import preferForOf from './prefer-for-of';
import preferFunctionType from './prefer-function-type';
import preferIncludes from './prefer-includes';
Expand Down Expand Up @@ -241,6 +242,7 @@ export default {
'prefer-as-const': preferAsConst,
'prefer-destructuring': preferDestructuring,
'prefer-enum-initializers': preferEnumInitializers,
'prefer-find': preferFind,
'prefer-for-of': preferForOf,
'prefer-function-type': preferFunctionType,
'prefer-includes': preferIncludes,
Expand Down
320 changes: 320 additions & 0 deletions packages/eslint-plugin/src/rules/prefer-find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,320 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { getScope, getSourceCode } from '@typescript-eslint/utils/eslint-utils';
import type {
RuleFix,
Scope,
SourceCode,
} from '@typescript-eslint/utils/ts-eslint';
import * as tsutils from 'ts-api-utils';
import type { Type } from 'typescript';

import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getStaticValue,
nullThrows,
} from '../util';

export default createRule({
name: 'prefer-find',
meta: {
docs: {
description:
'Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result',
requiresTypeChecking: true,
},
messages: {
preferFind: 'Prefer .find(...) instead of .filter(...)[0].',
preferFindSuggestion: 'Use .find(...) instead of .filter(...)[0].',
},
schema: [],
type: 'suggestion',
hasSuggestions: true,
},

defaultOptions: [],

create(context) {
const globalScope = getScope(context);
const services = getParserServices(context);
const checker = services.program.getTypeChecker();

interface FilterExpressionData {
isBracketSyntaxForFilter: boolean;
filterNode: TSESTree.Node;
}

function parseIfArrayFilterExpression(
expression: TSESTree.Expression,
): FilterExpressionData | undefined {
if (expression.type === AST_NODE_TYPES.SequenceExpression) {
// Only the last expression in (a, b, [1, 2, 3].filter(condition))[0] matters
const lastExpression = nullThrows(
expression.expressions.at(-1),
'Expected to have more than zero expressions in a sequence expression',
);
return parseIfArrayFilterExpression(lastExpression);
}

if (expression.type === AST_NODE_TYPES.ChainExpression) {
return parseIfArrayFilterExpression(expression.expression);
}

// Check if it looks like <<stuff>>(...), but not <<stuff>>?.(...)
if (
expression.type === AST_NODE_TYPES.CallExpression &&
!expression.optional
) {
const callee = expression.callee;
// Check if it looks like <<stuff>>.filter(...) or <<stuff>>['filter'](...),
// or the optional chaining variants.
if (callee.type === AST_NODE_TYPES.MemberExpression) {
const isBracketSyntaxForFilter = callee.computed;
if (isStaticMemberAccessOfValue(callee, 'filter', globalScope)) {
const filterNode = callee.property;

const filteredObjectType = getConstrainedTypeAtLocation(
services,
callee.object,
);

// As long as the object is a (possibly nullable) array,
// this is an Array.prototype.filter expression.
if (isArrayish(filteredObjectType)) {
return {
isBracketSyntaxForFilter,
filterNode,
};
}
}
}
}

return undefined;
}

/**
* Tells whether the type is a possibly nullable array/tuple or union thereof.
*/
function isArrayish(type: Type): boolean {
let isAtLeastOneArrayishComponent = false;
for (const unionPart of tsutils.unionTypeParts(type)) {
if (
tsutils.isIntrinsicNullType(unionPart) ||
tsutils.isIntrinsicUndefinedType(unionPart)
) {
continue;
}

// apparently checker.isArrayType(T[] & S[]) => false.
// so we need to check the intersection parts individually.
const isArrayOrIntersectionThereof = tsutils
.intersectionTypeParts(unionPart)
.every(
intersectionPart =>
checker.isArrayType(intersectionPart) ||
checker.isTupleType(intersectionPart),
);

if (!isArrayOrIntersectionThereof) {
// There is a non-array, non-nullish type component,
// so it's not an array.
return false;
}

isAtLeastOneArrayishComponent = true;
}

return isAtLeastOneArrayishComponent;
}

function getObjectIfArrayAtExpression(
node: TSESTree.CallExpression,
): TSESTree.Expression | undefined {
// .at() should take exactly one argument.
if (node.arguments.length !== 1) {
return undefined;
}

const atArgument = getStaticValue(node.arguments[0], globalScope);
if (atArgument != null && isTreatedAsZeroByArrayAt(atArgument.value)) {
const callee = node.callee;
if (
callee.type === AST_NODE_TYPES.MemberExpression &&
!callee.optional &&
isStaticMemberAccessOfValue(callee, 'at', globalScope)
) {
return callee.object;
}
}

return undefined;
}

/**
* Implements the algorithm for array indexing by `.at()` method.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at#parameters
*/
function isTreatedAsZeroByArrayAt(value: unknown): boolean {
const asNumber = Number(value);

if (isNaN(asNumber)) {
return true;
}

return Math.trunc(asNumber) === 0;
}

function isMemberAccessOfZero(
node: TSESTree.MemberExpressionComputedName,
): boolean {
const property = getStaticValue(node.property, globalScope);
// Check if it looks like <<stuff>>[0] or <<stuff>>['0'], but not <<stuff>>?.[0]
return (
!node.optional &&
property != null &&
isTreatedAsZeroByMemberAccess(property.value)
);
}

/**
* Implements the algorithm for array indexing by member operator.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices
*/
function isTreatedAsZeroByMemberAccess(value: unknown): boolean {
return String(value) === '0';
}

function generateFixToRemoveArrayElementAccess(
fixer: TSESLint.RuleFixer,
arrayNode: TSESTree.Expression,
wholeExpressionBeingFlagged: TSESTree.Expression,
sourceCode: SourceCode,
): RuleFix {
const tokenToStartDeletingFrom = nullThrows(
// The next `.` or `[` is what we're looking for.
// think of (...).at(0) or (...)[0] or even (...)["at"](0).
sourceCode.getTokenAfter(
arrayNode,
token => token.value === '.' || token.value === '[',
),
'Expected to find a member access token!',
);
return fixer.removeRange([
tokenToStartDeletingFrom.range[0],
wholeExpressionBeingFlagged.range[1],
]);
}

function generateFixToReplaceFilterWithFind(
fixer: TSESLint.RuleFixer,
filterExpression: FilterExpressionData,
): TSESLint.RuleFix {
return fixer.replaceText(
filterExpression.filterNode,
filterExpression.isBracketSyntaxForFilter ? '"find"' : 'find',
);
}

return {
// This query will be used to find things like `filteredResults.at(0)`.
CallExpression(node): void {
const object = getObjectIfArrayAtExpression(node);
if (object) {
const filterExpression = parseIfArrayFilterExpression(object);
if (filterExpression) {
context.report({
node,
messageId: 'preferFind',
suggest: [
{
messageId: 'preferFindSuggestion',
fix: (fixer): TSESLint.RuleFix[] => {
const sourceCode = getSourceCode(context);
return [
generateFixToReplaceFilterWithFind(
fixer,
filterExpression,
),
// Get rid of the .at(0) or ['at'](0).
generateFixToRemoveArrayElementAccess(
fixer,
object,
node,
sourceCode,
),
];
},
},
],
});
}
}
},

// This query will be used to find things like `filteredResults[0]`.
//
// Note: we're always looking for array member access to be "computed",
// i.e. `filteredResults[0]`, since `filteredResults.0` isn't a thing.
['MemberExpression[computed=true]'](
node: TSESTree.MemberExpressionComputedName,
): void {
if (isMemberAccessOfZero(node)) {
const object = node.object;
const filterExpression = parseIfArrayFilterExpression(object);
if (filterExpression) {
context.report({
node,
messageId: 'preferFind',
suggest: [
{
messageId: 'preferFindSuggestion',
fix: (fixer): TSESLint.RuleFix[] => {
const sourceCode = context.sourceCode;
return [
generateFixToReplaceFilterWithFind(
fixer,
filterExpression,
),
// Get rid of the [0].
generateFixToRemoveArrayElementAccess(
fixer,
object,
node,
sourceCode,
),
];
},
},
],
});
}
}
},
};
},
});

/**
* Answers whether the member expression looks like
* `x.memberName`, `x['memberName']`,
* or even `const mn = 'memberName'; x[mn]` (or optional variants thereof).
*/
function isStaticMemberAccessOfValue(
memberExpression:
| TSESTree.MemberExpressionComputedName
| TSESTree.MemberExpressionNonComputedName,
value: string,
scope?: Scope.Scope | undefined,
): boolean {
if (!memberExpression.computed) {
// x.memberName case.
return memberExpression.property.name === value;
}

// x['memberName'] cases.
const staticValueResult = getStaticValue(memberExpression.property, scope);
return staticValueResult != null && value === staticValueResult.value;
}
Loading