Skip to content

Commit 6a043c2

Browse files
authored
Document reduceRight alternative for no-array-reduce (#2457)
1 parent 1558cbe commit 6a043c2

File tree

3 files changed

+15
-6
lines changed

3 files changed

+15
-6
lines changed

docs/rules/no-array-reduce.md

+8
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ for (const element of array) {
5858
}
5959
```
6060

61+
```js
62+
let result = initialValue;
63+
64+
for (const element of array.toReversed()) { // Equivalent to .reduceRight()
65+
result += element;
66+
}
67+
```
68+
6169
## Options
6270

6371
### allowSimpleOperations

rules/no-array-reduce.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
const {isMethodCall} = require('./ast/index.js');
33
const {isNodeValueNotFunction, isArrayPrototypeProperty} = require('./utils/index.js');
44

5-
const MESSAGE_ID = 'no-reduce';
5+
const MESSAGE_ID_REDUCE = 'reduce';
6+
const MESSAGE_ID_REDUCE_RIGHT = 'reduceRight';
67
const messages = {
7-
[MESSAGE_ID]: '`Array#{{method}}()` is not allowed',
8+
[MESSAGE_ID_REDUCE]: '`Array#reduce()` is not allowed. Prefer other types of loop for readability.',
9+
[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.',
810
};
911

1012
const cases = [
@@ -104,8 +106,7 @@ const create = context => {
104106
const methodNode = getMethodNode(callExpression);
105107
yield {
106108
node: methodNode,
107-
messageId: MESSAGE_ID,
108-
data: {method: methodNode.name},
109+
messageId: methodNode.name,
109110
};
110111
}
111112
},

test/no-array-reduce.mjs

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import {getTester} from './utils/test.mjs';
44

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

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

1010
test({
1111
valid: [

0 commit comments

Comments
 (0)