Skip to content

Commit

Permalink
Fix: dot-notation autofix produces errors on parenthesized computed k…
Browse files Browse the repository at this point in the history
…eys (#8330)

This commit updates the dot-notation autofixer logic to ensure that parenthesized computed keys are handled correctly. Previously, the rule didn't account for the possibility that a computed key might be parenthesized, so it ended up using the parens instead of the square brackets for the fix range.
  • Loading branch information
not-an-aardvark authored and gyandeeps committed Mar 27, 2017
1 parent 2d883d7 commit 6c819d8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/rules/dot-notation.js
Expand Up @@ -4,6 +4,12 @@
*/
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -64,12 +70,10 @@ module.exports = {
propertyValue: JSON.stringify(node.property.value)
},
fix(fixer) {
const leftBracket = sourceCode.getTokenBefore(node.property);
const rightBracket = sourceCode.getTokenAfter(node.property);
const textBeforeProperty = sourceCode.text.slice(leftBracket.range[1], node.property.range[0]);
const textAfterProperty = sourceCode.text.slice(node.property.range[1], rightBracket.range[0]);
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);

if (textBeforeProperty.trim() || textAfterProperty.trim()) {
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {

// Don't perform any fixes if there are comments inside the brackets.
return null;
Expand Down
15 changes: 15 additions & 0 deletions tests/lib/rules/dot-notation.js
Expand Up @@ -153,6 +153,21 @@ ruleTester.run("dot-notation", rule, {
options: [{ allowKeywords: false }],
errors: [{ message: ".while is a syntax error." }],
output: null // Not fixed due to comment
},
{
code: "foo[('bar')]",
output: "foo.bar",
errors: [{ message: "[\"bar\"] is better written in dot notation." }]
},
{
code: "foo[(null)]",
output: "foo.null",
errors: [{ message: "[null] is better written in dot notation." }]
},
{
code: "(foo)['bar']",
output: "(foo).bar",
errors: [{ message: "[\"bar\"] is better written in dot notation." }]
}
]
});

0 comments on commit 6c819d8

Please sign in to comment.