Skip to content

Commit

Permalink
no-array-for-each: Handle ChainExpression correctly (#1772)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Mar 30, 2022
1 parent 5c16f4a commit e615a37
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 61 deletions.
14 changes: 10 additions & 4 deletions rules/no-array-for-each.js
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
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

0 comments on commit e615a37

Please sign in to comment.