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

Add prefer-at rule #280

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/rules/prefer-at.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Prefer `.at()` method for negative index access.

<!-- More detailed description. Remove this comment. -->

This rule is fixable.

## Fail

```js
const foo = 'unicorn';
```

## Pass

```js
const foo = '🦄';
```
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ module.exports = {
'unicorn/prefer-array-flat-map': 'error',
'unicorn/prefer-array-index-of': 'error',
'unicorn/prefer-array-some': 'error',
'unicorn/prefer-at': 'error',
'unicorn/prefer-date-now': 'error',
'unicorn/prefer-default-parameters': 'error',
'unicorn/prefer-dom-node-append': 'error',
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ Configure it in `package.json`.
"unicorn/prefer-array-flat-map": "error",
"unicorn/prefer-array-index-of": "error",
"unicorn/prefer-array-some": "error",
"unicorn/prefer-at": "error",
"unicorn/prefer-date-now": "error",
"unicorn/prefer-default-parameters": "error",
"unicorn/prefer-dom-node-append": "error",
Expand Down Expand Up @@ -176,6 +177,7 @@ Each rule has emojis denoting:
| [prefer-array-flat-map](docs/rules/prefer-array-flat-map.md) | Prefer `.flatMap(…)` over `.map(…).flat()`. | ✅ | 🔧 |
| [prefer-array-index-of](docs/rules/prefer-array-index-of.md) | Prefer `Array#indexOf()` over `Array#findIndex()` when looking for the index of an item. | ✅ | 🔧 |
| [prefer-array-some](docs/rules/prefer-array-some.md) | Prefer `.some(…)` over `.find(…)`. | ✅ | |
| [prefer-at](docs/rules/prefer-at.md) | Prefer `.at()` method for negative index access. | ✅ | 🔧 |
| [prefer-date-now](docs/rules/prefer-date-now.md) | Prefer `Date.now()` to get the number of milliseconds since the Unix Epoch. | ✅ | 🔧 |
| [prefer-default-parameters](docs/rules/prefer-default-parameters.md) | Prefer default parameters over reassignment. | ✅ | 🔧 |
| [prefer-dom-node-append](docs/rules/prefer-dom-node-append.md) | Prefer `Node#append()` over `Node#appendChild()`. | ✅ | 🔧 |
Expand Down
71 changes: 71 additions & 0 deletions rules/prefer-at.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use strict';
const {getStaticValue} = require('eslint-utils');
const getDocumentationUrl = require('./utils/get-documentation-url');
const isSameReference = require('./utils/is-same-reference');
const replaceNodeOrTokenAndSpacesBefore = require('./utils/replace-node-or-token-and-spaces-before');

const MESSAGE_ID = 'prefer-at';
const messages = {
[MESSAGE_ID]: 'Prefer `.at()` method for negative index access.'
};

const selector = [
'MemberExpression',
'[optional!=true]',
'[computed=true]',
'[property.type="BinaryExpression"]',
'[property.operator="-"]',
'[property.left.type="MemberExpression"]',
'[property.left.optional!=true]',
'[property.left.computed=false]',
'[property.left.property.type="Identifier"]',
'[property.left.property.name="length"]'
].join('')

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
return {
[selector](node) {
const array = node.object;
const lengthObject = node.property.left.object;
if (!isSameReference(array, lengthObject)) {
return;
}

const offset = node.property.right;
const staticResult = getStaticValue(offset, context.getScope());
if (
!staticResult ||
!Number.isInteger(staticResult.value) ||
staticResult.value < 1
) {
return;
}

context.report({
node: node.property,
messageId: MESSAGE_ID,
/** @param {import('eslint').Rule.RuleFixer} fixer */
* fix(fixer) {
yield * replaceNodeOrTokenAndSpacesBefore(node.property.left, '', fixer, context.getSourceCode());
}
});
}
}
};

const schema = [];

module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer `.at()` method for negative index access.',
url: getDocumentationUrl(__filename)
},
fixable: 'code',
schema,
messages
}
};
31 changes: 31 additions & 0 deletions test/prefer-at.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import outdent from 'outdent';
import {getTester} from './utils/test.mjs';

const {test} = getTester(import.meta);


test.snapshot({
valid: [
'array.at(-1)',
'array.at(1)',
'array[0]',
'array.foo',
'array[-1]',
'array[array.length + 1]',
'array[array.length - 0]',
'array[-10 + array.length]',
'array[array.length - 1n]',
'array[+array.length - 1]',
'array[array.length - -1]',
'array[array.length - foo]',
'array[array.length + -10]',
'const OFFSET = -1; array[array.length + OFFSET];'
],
invalid: [
'array[array.length - 1]',
'array[array.length - 10]',
'array[ /**/ (( /**/ (( /**/ array.length /**/ )) /**/ - /**/ (( /**/ 10 /**/ )) /**/ )) /**/ ]',
'const OFFSET = 1; array[array.length - OFFSET];',
// 'array.at(array.length - 1)'
]
});
69 changes: 69 additions & 0 deletions test/snapshots/prefer-at.mjs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Snapshot report for `test/prefer-at.mjs`

The actual snapshot is saved in `prefer-at.mjs.snap`.

Generated by [AVA](https://avajs.dev).

## Invalid #1
1 | array[array.length - 1]

> Output

`␊
1 | array[ - 1]␊
`

> Error 1/1

`␊
> 1 | array[array.length - 1]␊
| ^^^^^^^^^^^^^^^^ Prefer \`.at()\` method for negative index access.␊
`

## Invalid #2
1 | array[array.length - 10]

> Output

`␊
1 | array[ - 10]␊
`

> Error 1/1

`␊
> 1 | array[array.length - 10]␊
| ^^^^^^^^^^^^^^^^^ Prefer \`.at()\` method for negative index access.␊
`

## Invalid #3
1 | array[ /**/ (( /**/ (( /**/ array.length /**/ )) /**/ - /**/ (( /**/ 10 /**/ )) /**/ )) /**/ ]

> Output

`␊
1 | array[ /**/ (( /**/ /**/ /**/ /**/ - /**/ (( /**/ 10 /**/ )) /**/ )) /**/ ]␊
`

> Error 1/1

`␊
> 1 | array[ /**/ (( /**/ (( /**/ array.length /**/ )) /**/ - /**/ (( /**/ 10 /**/ )) /**/ )) /**/ ]␊
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer \`.at()\` method for negative index access.␊
`

## Invalid #4
1 | const OFFSET = 1; array[array.length - OFFSET];

> Output

`␊
1 | const OFFSET = 1; array[ - OFFSET];␊
`

> Error 1/1

`␊
> 1 | const OFFSET = 1; array[array.length - OFFSET];␊
| ^^^^^^^^^^^^^^^^^^^^^ Prefer \`.at()\` method for negative index access.␊
`
Binary file added test/snapshots/prefer-at.mjs.snap
Binary file not shown.