Skip to content

Commit

Permalink
Update: 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 authored and kaicataldo committed Jun 7, 2017
1 parent 735cd09 commit 34c4020
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
25 changes: 24 additions & 1 deletion lib/rules/no-extra-parens.js
Expand Up @@ -255,6 +255,23 @@ 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 requiresTrailingSpace(node) {
const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
const rightParenToken = nextTwoTokens[0];
const tokenAfterRightParen = nextTwoTokens[1];
const tokenBeforeRightParen = sourceCode.getLastToken(node);

return rightParenToken && tokenAfterRightParen &&
!sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
!astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
}

/**
* Report the node
* @param {ASTNode} node node to evaluate
Expand All @@ -279,7 +296,7 @@ module.exports = {
return fixer.replaceTextRange([
leftParenToken.range[0],
rightParenToken.range[1]
], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource);
], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
}
});
}
Expand Down Expand Up @@ -488,12 +505,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
22 changes: 21 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,27 @@ 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(
"for ((foo['bar'])of baz);",
"for (foo['bar']of baz);",
"MemberExpression",
1,
{ parserOptions: { ecmaVersion: 2015 } }
),
invalid(
"() => (({ foo: 1 }).foo)",
"() => ({ foo: 1 }).foo",
Expand Down

0 comments on commit 34c4020

Please sign in to comment.