eslint-plugin-no-array-reduce
v1.0.62
Published
ESLint rule to disallow Array.reduce() method.
Downloads
13,725
Maintainers
Readme
eslint-plugin-no-array-reduce
ESLint rule to disallow Array.reduce()
method.
Method reduce()
in most cases can be written as map()
, filter()
etc. which benefits in code readability and makes it easier to maintain for future developers.
Subjectively there are still cases where you might want to use reduce()
with eslint-disable
.
There are many debates related to it:
Install
npm install --save-dev eslint-plugin-no-array-reduce
Then extend eslint config:
{
"extends": [
// ...
"plugin:no-array-reduce/recommended"
]
}
Fail
const products = [
{ name: 'milk', type: 'dairy' },
{ name: 'cheese', type: 'dairy' },
{ name: 'beef', type: 'meat' },
{ name: 'chicken', type: 'meat' },
];
// Add price to each product
const productsWithPrices = products.reduce((acc, product) => acc.concat({ ...product, price: 2.7 }), []);
// Filter dairy products
const dairies = products.reduce((acc, product) => (product.type === 'dairy' ? acc.concat(product) : acc), []);
// Group products by type
const productsByType = products.reduce(
(acc, product) => ({
...acc,
[product.type]: [...(acc[product.type] || []), product],
}),
[],
);
Pass
// Add price to each product
const productsWithPrices = products.map((product) => ({ ...product, price: 2.7 }));
// Filter dairy products
const dairies = products.filter((product) => product.type === 'dairy');
// Group products by type (ECMA stage 3 - https://github.com/tc39/proposal-array-grouping)
const productsByType = products.group((product) => product.type);
Contributing
All contributions are welcome!