Skip to content

Commit

Permalink
Fix: Add support for parens on left side for-loops (fixes: #8393)
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorHom committed Jun 2, 2017
1 parent 4df33e7 commit 4731ca7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
24 changes: 23 additions & 1 deletion lib/rules/no-extra-parens.js
Expand Up @@ -255,6 +255,22 @@ module.exports = {
!astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken);
}

/**
* Determines whether a node should be followed by an additional space when removing parens
* @param {ASTNode} node node to evaluate; must be surrounded by parentheses
* @returns {boolean} `true` if a space should be inserted after the node
* @private
*/
function requiresAfterSpace(node) {
const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
const rightParenToken = nextTwoTokens[0];
const tokenAfterRightParen = nextTwoTokens[1];

return rightParenToken && tokenAfterRightParen &&
!sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
tokenAfterRightParen.type === "Keyword";
}

/**
* Report the node
* @param {ASTNode} node node to evaluate
Expand All @@ -279,7 +295,7 @@ module.exports = {
return fixer.replaceTextRange([
leftParenToken.range[0],
rightParenToken.range[1]
], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource);
], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresAfterSpace(node) ? " " : ""));
}
});
}
Expand Down Expand Up @@ -488,12 +504,18 @@ module.exports = {
if (hasExcessParens(node.right)) {
report(node.right);
}
if (hasExcessParens(node.left)) {
report(node.left);
}
},

ForOfStatement(node) {
if (hasExcessParens(node.right)) {
report(node.right);
}
if (hasExcessParens(node.left)) {
report(node.left);
}
},

ForStatement(node) {
Expand Down
15 changes: 14 additions & 1 deletion tests/lib/rules/no-extra-parens.js
Expand Up @@ -41,7 +41,6 @@ function invalid(code, output, type, line, config) {
if (line) {
result.errors[0].line = line;
}

return result;
}

Expand Down Expand Up @@ -996,6 +995,20 @@ ruleTester.run("no-extra-parens", rule, {
1,
{ parserOptions: { ecmaVersion: 2015 } }
),
invalid(
"for ((foo) of bar);",
"for (foo of bar);",
"Identifier",
1,
{ parserOptions: { ecmaVersion: 2015 } }
),
invalid(
"for ((foo)in bar);",
"for (foo in bar);",
"Identifier",
1,
{ parserOptions: { ecmaVersion: 2015 } }
),
invalid(
"() => (({ foo: 1 }).foo)",
"() => ({ foo: 1 }).foo",
Expand Down

0 comments on commit 4731ca7

Please sign in to comment.