Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no-array-for-each: Handle ChainExpression correctly #1772

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions rules/no-array-for-each.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@ function isFunctionParameterVariableReassigned(callbackFunction, context) {
});
}

const isExpressionStatement = node => {
if (node.type === 'ChainExpression') {
node = node.parent;
}

return node.type === 'ExpressionStatement';
};

function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context}) {
const sourceCode = context.getSourceCode();
// Check `CallExpression`
Expand All @@ -313,14 +321,12 @@ function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context
return false;
}

// Check `CallExpression.parent`
if (callExpression.parent.type !== 'ExpressionStatement') {
// Check ancestors, we only fix `ExpressionStatement`
if (!isExpressionStatement(callExpression.parent)) {
return false;
}

// Check `CallExpression.callee`
// Because of `ChainExpression` wrapper, `foo?.forEach()` is already failed on previous check keep this just for safety
/* c8 ignore next 3 */
if (callExpression.callee.optional) {
return false;
}
Expand Down
2 changes: 2 additions & 0 deletions test/no-array-for-each.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ test.snapshot({
bar(arguments)
})
`,
'a = foo?.bar.forEach((element) => bar(element));',

// Auto-fix
outdent`
Expand Down Expand Up @@ -230,6 +231,7 @@ test.snapshot({
});
`,
'foo.forEach((element, index) => bar(element, index));',
'foo?.bar.forEach((element) => bar(element));',
// Array is parenthesized
'(foo).forEach((element, index) => bar(element, index))',
'(0, foo).forEach((element, index) => bar(element, index))',
Expand Down