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

feat(eslint-plugin): [prefer-at] create rule #6411

Closed
wants to merge 16 commits into from
Closed
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
40 changes: 40 additions & 0 deletions packages/eslint-plugin/docs/rules/prefer-at.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
description: Enforce the use of `array.at(-1)` instead of `array[array.length - 1]`
---

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

There are two ways to get the last item of the array:
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved

- `arr[arr.length - 1]`: getting an item by index calculated relative to the length of the array.
- `arr.at(-1)`: getting an item by the `at` method. [Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at)
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved

`arr.at(-1)` is a cleaner equivalent to `arr[arr.length - 1]`.

## Examples

<!--tabs-->

### ❌ Incorrect

```ts
let arr = [1, 2, 3];
let a = arr[arr.length - 1];
```

### ✅ Correct

```ts
let arr = [1, 2, 3];
let a = arr.at(-1);
```

<!--/tabs-->

## When Not To Use It

If you support a browser that does not match
[this table](https://caniuse.com/mdn-javascript_builtins_array_at)
or use `node.js < 16.6.0` and don't include the polyfill
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -94,6 +94,7 @@ import objectCurlySpacing from './object-curly-spacing';
import paddingLineBetweenStatements from './padding-line-between-statements';
import parameterProperties from './parameter-properties';
import preferAsConst from './prefer-as-const';
import preferAt from './prefer-at';
import preferEnumInitializers from './prefer-enum-initializers';
import preferForOf from './prefer-for-of';
import preferFunctionType from './prefer-function-type';
Expand Down Expand Up @@ -227,6 +228,7 @@ export default {
'padding-line-between-statements': paddingLineBetweenStatements,
'parameter-properties': parameterProperties,
'prefer-as-const': preferAsConst,
'prefer-at': preferAt,
'prefer-enum-initializers': preferEnumInitializers,
'prefer-for-of': preferForOf,
'prefer-function-type': preferFunctionType,
Expand Down
77 changes: 77 additions & 0 deletions packages/eslint-plugin/src/rules/prefer-at.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import * as util from '../util';

export default util.createRule({
name: 'prefer-at',
meta: {
type: 'suggestion',
fixable: 'code',
docs: {
description:
'Enforce the use of `array.at(-1)` instead of `array[array.length - 1]`',
recommended: false,
},
messages: {
preferAt:
'Expected a `{{name}}.at(-1)` instead of `{{name}}[{{name}}.length - 1]`.',
},
schema: [],
},
defaultOptions: [],
create(context) {
class UnknownNodeError extends Error {
public constructor(node: TSESTree.Node) {
super(`UnknownNode ${node.type}`);
}
}

function getName(node: TSESTree.Node): string {
switch (node.type) {
case AST_NODE_TYPES.PrivateIdentifier:
return `#${node.name}`;
case AST_NODE_TYPES.Identifier:
return node.name;
case AST_NODE_TYPES.ThisExpression:
return 'this';
case AST_NODE_TYPES.MemberExpression:
return `${getName(node.object)}.${getName(node.property)}`;
default:
throw new UnknownNodeError(node);
}
}

return {
MemberExpression(node: TSESTree.MemberExpression): void {
try {
if (
node.property.type !== AST_NODE_TYPES.BinaryExpression ||
node.property.operator !== '-' ||
node.property.right.type !== AST_NODE_TYPES.Literal ||
node.property.right.value !== 1
) {
return;
}
const objectName = getName(node.object);
const propertyLeftName = getName(node.property.left);
if (`${objectName}.length` === propertyLeftName) {
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved
context.report({
messageId: 'preferAt',
data: {
name: objectName,
},
node,
fix: fixer => fixer.replaceText(node, `${objectName}.at(-1)`),
});
}
} catch (error) {
if (error instanceof UnknownNodeError) {
return;
}
throw error;
}
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved
},
};
},
});
67 changes: 67 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-at.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import rule from '../../src/rules/prefer-at';
import { RuleTester } from '../RuleTester';

const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});

ruleTester.run('prefer-at', rule, {
valid: [
'const a = arr.at(-1);',
'const a = this.arr.at(-1);',
'const a = this.#arr.at(-1);',
'const a = this.#prop.arr.at(-1);',
'const a = arr[arr.length + 1];',
'const a = (arr ? b : c)[arr.length - 1];',
],
invalid: [
{
code: 'const a = arr[arr.length - 1];',
errors: [
{
messageId: 'preferAt',
data: {
name: 'arr',
},
},
],
output: 'const a = arr.at(-1);',
},
{
code: 'const a = this.arr[this.arr.length - 1];',
errors: [
{
messageId: 'preferAt',
data: {
name: 'this.arr',
},
},
],
output: 'const a = this.arr.at(-1);',
},
{
code: 'const a = this.#arr[this.#arr.length - 1];',
errors: [
{
messageId: 'preferAt',
data: {
name: 'this.#arr',
},
},
],
output: 'const a = this.#arr.at(-1);',
},
{
code: 'const a = this.#prop.arr[this.#prop.arr.length - 1];',
errors: [
{
messageId: 'preferAt',
data: {
name: 'this.#prop.arr',
},
},
],
output: 'const a = this.#prop.arr.at(-1);',
},
],
});