Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
28 changes: 27 additions & 1 deletion docs/rules/no-array-reduce.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Disallow `Array#reduce()` and `Array#reduceRight()`

`Array#reduce()` and `Array#reduceRight()` usually result in [hard-to-read](https://twitter.com/jaffathecake/status/1213077702300852224) and [less performant](https://www.richsnapp.com/article/2019/06-09-reduce-spread-anti-pattern) code. In almost every case, it can be replaced by `.map`, `.filter`, or a `for-of` loop. It's only somewhat useful in the rare case of summing up numbers.
`Array#reduce()` and `Array#reduceRight()` usually result in [hard-to-read](https://twitter.com/jaffathecake/status/1213077702300852224) and [less performant](https://www.richsnapp.com/article/2019/06-09-reduce-spread-anti-pattern) code. In almost every case, it can be replaced by `.map`, `.filter`, or a `for-of` loop.

It's only somewhat useful in the rare case of summing up numbers, which is allowed by default.

Use `eslint-disable` comment if you really need to use it.

Expand Down Expand Up @@ -39,10 +41,34 @@ Array.prototype.reduce.call(array, reducer);
array.reduce(reducer, initialValue);
```

```js
array.reduce((total, value) => total + value, 0);
```

```js
let result = initialValue;

for (const element of array) {
result += element;
}
```
## Options

### allowSimpleOperations

Type: `boolean`\
Default: `true`

Allow simple operations (like addition, subtraction, etc.) in a `reduce` call.

Pass `"allowSimpleOperations": false` to disable reduce completely.

```js
// eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": true}]
arr.reduce((total, item) => total + item) // Passes
```

```js
// eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": false}]
arr.reduce((total, item) => total + item) // Fails
```
43 changes: 41 additions & 2 deletions rules/no-array-reduce.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';
const {get} = require('lodash');
const {methodCallSelector} = require('./selectors/index.js');
const {arrayPrototypeMethodSelector, notFunctionSelector, matches} = require('./selectors/index.js');
const {isNumeric} = require('./utils/numeric.js');

const MESSAGE_ID = 'no-reduce';
const messages = {
Expand Down Expand Up @@ -34,14 +36,50 @@ const selector = matches([
].join(''),
]);

const create = () => {
const schema = [
{
type: 'object',
properties: {
allowSimpleOperations: {
type: 'boolean',
default: true,
},
},
},
];

const create = context => {
const {allowSimpleOperations} = {allowSimpleOperations: true, ...context.options[0]};

return {
[selector](node) {
return {
const callback = get(node, 'parent.parent.arguments[0]', {});
const problem = {
node,
messageId: MESSAGE_ID,
data: {method: node.name},
};

if (!allowSimpleOperations) {
return problem;
}

if (callback.type === 'ArrowFunctionExpression' && callback.body.type === 'BinaryExpression') {
return;
}

if ((callback.type === 'ArrowFunctionExpression' || callback.type === 'FunctionExpression') &&
callback.body.type === 'BlockStatement' &&
callback.body.body[0].type === 'ReturnStatement' &&
callback.body.body[0].argument.type === 'BinaryExpression') {
return;
}

if (isNumeric(get(node, 'parent.parent.arguments[1]'))) {
return;
}

return problem;
},
};
};
Expand All @@ -53,6 +91,7 @@ module.exports = {
docs: {
description: 'Disallow `Array#reduce()` and `Array#reduceRight()`.',
},
schema,
messages,
},
};
2 changes: 1 addition & 1 deletion rules/utils/numeric.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const isDecimalIntegerNode = node => isNumber(node) && isDecimalInteger(node.raw

const isNumber = node => typeof node.value === 'number';
const isBigInt = node => Boolean(node.bigint);
const isNumeric = node => isNumber(node) || isBigInt(node);
const isNumeric = node => node ? isNumber(node) || isBigInt(node) : false;
const isLegacyOctal = node => isNumber(node) && /^0\d+$/.test(node.raw);

function getPrefix(text) {
Expand Down
69 changes: 64 additions & 5 deletions test/no-array-reduce.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,22 @@ test({
// Second argument is not a function
...notFunctionTypes.map(data => `Array.prototype.reduce.call(foo, ${data})`),

].flatMap(code => [code, code.replace('reduce', 'reduceRight')]),
invalid: [
// Option: allowSimpleOperations
'arr.reduce((total, item) => total + item)',
'arr.reduce((total, item) => { return total - item })',
'arr.reduce(function (total, item) { return total * item })',
'arr.reduce((total, item) => total + item, 0)',
'arr.reduce(function (total, item) { return total + item }, 0)',
'arr.reduce(function (total, item) { return total + item })',
'arr.reduce((total, item) => { return total - item }, 0 )',
'arr.reduce(function (total, item) { return total * item }, 0)',
outdent`
arr.reduce((total, item) => {
const multiplier = 100;
return (total / item) * multiplier;
}, 0)
`,
'arr.reduce((total, item) => { return total + item }, 0)',
].flatMap(testCase => [testCase, testCase.replace('reduce', 'reduceRight')]),
invalid: [
'arr.reduce((str, item) => str += item, "")',
outdent`
arr.reduce((obj, item) => {
Expand All @@ -120,5 +130,54 @@ test({
'[].reduce.apply(arr, [sum]);',
'Array.prototype.reduce.apply(arr, [(s, i) => s + i])',
'Array.prototype.reduce.apply(arr, [sum]);',
].flatMap(code => [{code, errors: errorsReduce}, {code: code.replace('reduce', 'reduceRight'), errors: errorsReduceRight}]),

// Option: allowSimpleOperations
{
code: 'arr.reduce((total, item) => total + item)',
options: [{allowSimpleOperations: false}],
},
{
code: 'arr.reduce((total, item) => { return total - item })',
options: [{allowSimpleOperations: false}],
},
{
code: 'arr.reduce(function (total, item) { return total * item })',
options: [{allowSimpleOperations: false}],
},
{
code: 'arr.reduce((total, item) => total + item, 0)',
options: [{allowSimpleOperations: false}],
},
{
code: 'arr.reduce((total, item) => { return total - item }, 0 )',
options: [{allowSimpleOperations: false}],
},
{
code: 'arr.reduce(function (total, item) { return total * item }, 0)',
options: [{allowSimpleOperations: false}],
},
{
code: outdent`
arr.reduce((total, item) => {
const multiplier = 100;
return (total / item) * multiplier;
}, 0)
`,
options: [{allowSimpleOperations: false}],
},
].flatMap(testCase => {
const {code, options} = testCase;

if (options) {
return [
{code, errors: errorsReduce, options},
{code: code.replace('reduce', 'reduceRight'), errors: errorsReduceRight, options},
];
}

return [
{code: testCase, errors: errorsReduce},
{code: testCase.replace('reduce', 'reduceRight'), errors: errorsReduceRight},
];
}),
});