Skip to content

Latest commit

Β 

History

History
92 lines (66 loc) Β· 2.18 KB

File metadata and controls

92 lines (66 loc) Β· 2.18 KB

Disallow Array#reduce() and Array#reduceRight()

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

Array#reduce() and Array#reduceRight() usually result in hard-to-read and less performant 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 or disable the rule entirely if you prefer functional programming.

This rule is not fixable.

Examples

// ❌
array.reduce(reducer);

// βœ…
// eslint-disable-next-line unicorn/no-array-reduce
array.reduce(reducer);
// ❌
array.reduce(reducer, initialValue);

// βœ…
let result = initialValue;

for (const element of array) {
	result += element;
}
// βœ…
array.reduce((total, value) => total + value);
// ❌
array.reduceRight(reducer, initialValue);

// βœ…
let result = initialValue;

for (const element of array.toReversed()) { // Equivalent to .reduceRight()
	result += element;
}
// ❌
[].reduce.call(array, reducer);
// ❌
[].reduce.apply(array, [reducer, initialValue]);
// ❌
Array.prototype.reduce.call(array, reducer);

Options

allowSimpleOperations

Type: boolean
Default: true

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

Set it to false to disable reduce completely.

/* eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": true}] */
// βœ…
array.reduce((total, item) => total + item)
/* eslint unicorn/no-array-reduce: ["error", {"allowSimpleOperations": false}] */
// ❌
array.reduce((total, item) => total + item)