Skip to content

Commit

Permalink
Fix: object-shorthand autofix produces errors on parenthesized functi…
Browse files Browse the repository at this point in the history
…ons (#8328)

The object-shorthand autofixer would previously produce invalid syntax when replacing a parenthesized function property with a method. This commit updates the fixer to replace the function text, excluding any closing parens that might appear after it.
  • Loading branch information
not-an-aardvark authored and gyandeeps committed Mar 27, 2017
1 parent cd9b774 commit 2d883d7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/rules/object-shorthand.js
Expand Up @@ -230,15 +230,21 @@ module.exports = {
const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;

return fixer.replaceTextRange([firstKeyToken.range[0], tokenBeforeParams.range[1]], keyPrefix + keyText);
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
);
}
const arrowToken = sourceCode.getTokens(node.value).find(token => token.value === "=>");
const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken);
const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")";
const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]);
const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`;

return fixer.replaceTextRange([firstKeyToken.range[0], arrowToken.range[1]], keyPrefix + keyText + newParamText);
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1])
);

}

Expand Down
11 changes: 11 additions & 0 deletions tests/lib/rules/object-shorthand.js
Expand Up @@ -973,6 +973,17 @@ ruleTester.run("object-shorthand", rule, {
`,
options: ["always", { avoidExplicitReturnArrows: true }],
errors: [METHOD_ERROR]
},
{
code: "({ a: (function(){ return foo; }) })",
output: "({ a(){ return foo; } })",
errors: [METHOD_ERROR]
},
{
code: "({ a: (() => { return foo; }) })",
output: "({ a() { return foo; } })",
options: ["always", { avoidExplicitReturnArrows: true }],
errors: [METHOD_ERROR]
}
]
});

0 comments on commit 2d883d7

Please sign in to comment.