eslint-plugin-no-array-reduce

1.0.62 • Public • Published

eslint-plugin-no-array-reduce

npm version npm downloads CI semantic-release prettier TypeScript

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);

CodeSandbox

Contributing

All contributions are welcome!

Package Sidebar

Install

npm i eslint-plugin-no-array-reduce

Weekly Downloads

2,670

Version

1.0.62

License

MIT

Unpacked Size

6.83 kB

Total Files

4

Last publish

Collaborators

  • marko424