Skip to content

Commit e615a37

Browse files
authored
no-array-for-each: Handle ChainExpression correctly (#1772)
1 parent 5c16f4a commit e615a37

File tree

4 files changed

+95
-61
lines changed

4 files changed

+95
-61
lines changed

rules/no-array-for-each.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,14 @@ function isFunctionParameterVariableReassigned(callbackFunction, context) {
302302
});
303303
}
304304

305+
const isExpressionStatement = node => {
306+
if (node.type === 'ChainExpression') {
307+
node = node.parent;
308+
}
309+
310+
return node.type === 'ExpressionStatement';
311+
};
312+
305313
function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context}) {
306314
const sourceCode = context.getSourceCode();
307315
// Check `CallExpression`
@@ -313,14 +321,12 @@ function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context
313321
return false;
314322
}
315323

316-
// Check `CallExpression.parent`
317-
if (callExpression.parent.type !== 'ExpressionStatement') {
324+
// Check ancestors, we only fix `ExpressionStatement`
325+
if (!isExpressionStatement(callExpression.parent)) {
318326
return false;
319327
}
320328

321329
// Check `CallExpression.callee`
322-
// Because of `ChainExpression` wrapper, `foo?.forEach()` is already failed on previous check keep this just for safety
323-
/* c8 ignore next 3 */
324330
if (callExpression.callee.optional) {
325331
return false;
326332
}

test/no-array-for-each.mjs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ test.snapshot({
196196
bar(arguments)
197197
})
198198
`,
199+
'a = foo?.bar.forEach((element) => bar(element));',
199200

200201
// Auto-fix
201202
outdent`
@@ -230,6 +231,7 @@ test.snapshot({
230231
});
231232
`,
232233
'foo.forEach((element, index) => bar(element, index));',
234+
'foo?.bar.forEach((element) => bar(element));',
233235
// Array is parenthesized
234236
'(foo).forEach((element, index) => bar(element, index))',
235237
'(0, foo).forEach((element, index) => bar(element, index))',

0 commit comments

Comments
 (0)