Skip to content

Commit

Permalink
Document reduceRight alternative for no-array-reduce (#2457)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Sep 29, 2024
1 parent 1558cbe commit 6a043c2
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
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,
};
}
},
Expand Down
4 changes: 2 additions & 2 deletions test/no-array-reduce.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {getTester} from './utils/test.mjs';

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

const errorsReduce = [{messageId: 'no-reduce', data: {method: 'reduce'}}];
const errorsReduceRight = [{messageId: 'no-reduce', data: {method: 'reduceRight'}}];
const errorsReduce = [{messageId: 'reduce'}];
const errorsReduceRight = [{messageId: 'reduceRight'}];

test({
valid: [
Expand Down

0 comments on commit 6a043c2

Please sign in to comment.