2 * @fileoverview Rule to disallow whitespace before properties
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils = require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
22 description: "disallow whitespace before properties",
23 category: "Stylistic Issues",
25 url: "https://eslint.org/docs/rules/no-whitespace-before-property"
28 fixable: "whitespace",
32 unexpectedWhitespace: "Unexpected whitespace before property {{propName}}."
37 const sourceCode = context.getSourceCode();
39 //--------------------------------------------------------------------------
41 //--------------------------------------------------------------------------
44 * Reports whitespace before property token
45 * @param {ASTNode} node the node to report in the event of an error
46 * @param {Token} leftToken the left token
47 * @param {Token} rightToken the right token
51 function reportError(node, leftToken, rightToken) {
54 messageId: "unexpectedWhitespace",
56 propName: sourceCode.getText(node.property)
59 let replacementText = "";
61 if (!node.computed && !node.optional && astUtils.isDecimalInteger(node.object)) {
64 * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError.
65 * Don't fix this case.
70 // Don't fix if comments exist.
71 if (sourceCode.commentsExistBetween(leftToken, rightToken)) {
76 replacementText = "?.";
77 } else if (!node.computed) {
78 replacementText = ".";
81 return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText);
86 //--------------------------------------------------------------------------
88 //--------------------------------------------------------------------------
91 MemberExpression(node) {
95 if (!astUtils.isTokenOnSameLine(node.object, node.property)) {
100 rightToken = sourceCode.getTokenBefore(node.property, astUtils.isOpeningBracketToken);
101 leftToken = sourceCode.getTokenBefore(rightToken, node.optional ? 1 : 0);
103 rightToken = sourceCode.getFirstToken(node.property);
104 leftToken = sourceCode.getTokenBefore(rightToken, 1);
107 if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) {
108 reportError(node, leftToken, rightToken);