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

Enhance no-array-for-each to handle optional chaining #1753

Merged
merged 27 commits into from
Apr 1, 2022
Merged
Show file tree
Hide file tree
Changes from 14 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
6 changes: 6 additions & 0 deletions docs/rules/no-array-for-each.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ array.forEach(element => {
});
```

```js
array?.forEach(element => {
bar(element);
});
```

```js
array.forEach((element, index) => {
bar(element, index);
Expand Down
44 changes: 38 additions & 6 deletions rules/no-array-for-each.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
isSemicolonToken,
isClosingParenToken,
findVariable,
hasSideEffect,
} = require('eslint-utils');
const {methodCallSelector, referenceIdentifierSelector} = require('./selectors/index.js');
const {extendFixRange} = require('./fix/index.js');
Expand Down Expand Up @@ -73,6 +74,7 @@ function getFixFunction(callExpression, functionInfo, context) {
const parameters = callback.params;
const array = callExpression.callee.object;
const {returnStatements} = functionInfo.get(callback);
const isOptionalChaining = callExpression.callee.optional;

const getForOfLoopHeadText = () => {
const [elementText, indexText] = parameters.map(parameter => sourceCode.getText(parameter));
Expand Down Expand Up @@ -182,6 +184,11 @@ function getFixFunction(callExpression, functionInfo, context) {
return true;
};

const getIfCondition = (calleeObject) => {
if (calleeObject.type === 'Identifier') return calleeObject.name
return sourceCode.getText(calleeObject)
}

function * removeCallbackParentheses(fixer) {
// Opening parenthesis tokens already included in `getForOfLoopHeadRange`
const closingParenthesisTokens = getParentheses(callback, sourceCode)
Expand Down Expand Up @@ -228,7 +235,7 @@ function getFixFunction(callExpression, functionInfo, context) {
yield * replaceReturnStatement(returnStatement, fixer);
}

const expressionStatementLastToken = sourceCode.getLastToken(callExpression.parent);
const expressionStatementLastToken = sourceCode.getLastToken(isOptionalChaining ? callExpression.parent.parent : callExpression.parent);
// Remove semicolon if it's not needed anymore
// foo.forEach(bar => {});
// ^
Expand All @@ -238,6 +245,11 @@ function getFixFunction(callExpression, functionInfo, context) {

yield * fixSpaceAroundKeyword(fixer, callExpression.parent, sourceCode);

if (isOptionalChaining) {
const ifCondition = callExpression.callee.object.type === 'Identifier' ? callExpression.callee.object.name : sourceCode.getText(callExpression.callee.object)
yield fixer.insertTextBefore(callExpression, `if (${ifCondition}) `);
}

// Prevent possible variable conflicts
yield * extendFixRange(fixer, callExpression.parent.range);
};
Expand Down Expand Up @@ -302,7 +314,18 @@ function isFunctionParameterVariableReassigned(callbackFunction, context) {
});
}

function isSuggestable(callExpression, context) {
const isOptionalChaining = callExpression.callee.optional;

if (!isOptionalChaining) {
return false;
}

return callExpression.callee.object.type === 'CallExpression' && hasSideEffect(callExpression.callee.object, context.getSourceCode());
}

function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context}) {
const isOptionalChaining = callExpression.callee.optional;
const sourceCode = context.getSourceCode();
// Check `CallExpression`
if (
Expand All @@ -314,14 +337,15 @@ function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context
}

// Check `CallExpression.parent`
if (callExpression.parent.type !== 'ExpressionStatement') {
if (callExpression.parent.type !== 'ExpressionStatement' && callExpression.parent.type !== 'ChainExpression') {
fisker marked this conversation as resolved.
Show resolved Hide resolved
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) {
if (isOptionalChaining && callExpression.parent.parent.type !== 'ExpressionStatement') {
fisker marked this conversation as resolved.
Show resolved Hide resolved
return false;
}

if (isOptionalChaining && callExpression.callee.object.type !== 'Identifier' && callExpression.callee.object.type !== 'MemberExpression') {
fisker marked this conversation as resolved.
Show resolved Hide resolved
return false;
}

Expand Down Expand Up @@ -414,6 +438,13 @@ const create = context => {
problem.fix = getFixFunction(node, functionInfo, context);
}

if (isSuggestable(node, context)) {
problem.suggest = [{
desc: 'Call function twice because it has no side effects',
fix: getFixFunction(node, functionInfo, context),
}];
}

yield problem;
}
},
Expand All @@ -429,6 +460,7 @@ module.exports = {
description: 'Prefer `for…of` over `Array#forEach(…)`.',
},
fixable: 'code',
hasSuggestions: true,
messages,
},
};