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

Document reduceRight alternative for no-array-reduce #2457

Merged
merged 5 commits into from
Sep 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
8 changes: 8 additions & 0 deletions docs/rules/no-array-reduce.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ for (const element of array) {
}
```

```js
let result = initialValue;

for (const element of array.toReversed()) { // Equivalent to .reduceRight()
result += element;
}
```

## Options

### allowSimpleOperations
Expand Down
9 changes: 5 additions & 4 deletions rules/no-array-reduce.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
const {isMethodCall} = require('./ast/index.js');
const {isNodeValueNotFunction, isArrayPrototypeProperty} = require('./utils/index.js');

const MESSAGE_ID = 'no-reduce';
const MESSAGE_ID_REDUCE = 'reduce';
const MESSAGE_ID_REDUCE_RIGHT = 'reduceRight';
const messages = {
[MESSAGE_ID]: '`Array#{{method}}()` is not allowed',
[MESSAGE_ID_REDUCE]: '`Array#reduce()` is not allowed. Prefer other types of loop for readability.',
[MESSAGE_ID_REDUCE_RIGHT]: '`Array#reduceRight()` is not allowed. Prefer other types of loop for readability. You may want to call `Array#toReversed()` before looping it.',
};

const cases = [
Expand Down Expand Up @@ -104,8 +106,7 @@ const create = context => {
const methodNode = getMethodNode(callExpression);
yield {
node: methodNode,
messageId: MESSAGE_ID,
data: {method: methodNode.name},
messageId: methodNode.name,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pattern seen in

};
}
},
Expand Down
Loading