Skip to content

Commit

Permalink
no-array-for-each: Add ignoreNamedIdentifier option
Browse files Browse the repository at this point in the history
  • Loading branch information
azat-io committed Nov 15, 2024
1 parent 0d91fe8 commit 588c866
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
14 changes: 14 additions & 0 deletions docs/rules/no-array-for-each.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,17 @@ for (const [index, element] of array.entries()) {
bar(element, index, array);
}
```
## Options
### ignoreNamedIdentifier
Type: `boolean`\
Default: `false`
Ignores the rule when the callback is function identifier.
```js
// Pass
array.forEach(bar);
```
22 changes: 22 additions & 0 deletions rules/no-array-for-each.js
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ const create = context => {
const allIdentifiers = [];
const functionInfo = new Map();
const {sourceCode} = context;
const {ignoreNamedIdentifier} = context.options[0] || {};

context.on(functionTypes, node => {
functionStack.push(node);
Expand Down Expand Up @@ -420,6 +421,13 @@ const create = context => {
method: 'forEach',
})
|| isNodeMatches(node.callee.object, ignoredObjects)
|| (
isMethodCall(node, {
method: 'forEach',
})
&& ignoreNamedIdentifier
&& node.arguments[0].type === 'Identifier'
)
) {
return;
}
Expand Down Expand Up @@ -468,6 +476,19 @@ const create = context => {
});
};

const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
ignoreNamedIdentifier: {
type: 'boolean',
default: false,
},
},
},
];

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
Expand All @@ -479,6 +500,7 @@ module.exports = {
},
fixable: 'code',
hasSuggestions: true,
schema,
messages,
},
};
27 changes: 27 additions & 0 deletions test/no-array-for-each.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -680,3 +680,30 @@ test({
},
],
});

test({
valid: [
{
code: `foo.forEach(bar)`,
options: [
{
ignoreNamedIdentifier: true,
},
],
},
],
invalid: [
{
code: `foo.forEach(element => bar(element))`,
options: [
{
ignoreNamedIdentifier: true,
},
],
output: outdent`
for (const element of foo) bar(element)
`,
errors: 1,
},
],
})

0 comments on commit 588c866

Please sign in to comment.