2 * @fileoverview Rule to disallow unnecessary computed property keys in object literals
3 * @author Burak Yigit Kaya
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const lodash
= require("lodash");
12 const astUtils
= require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
23 description
: "disallow unnecessary computed property keys in objects and classes",
24 category
: "ECMAScript 6",
26 url
: "https://eslint.org/docs/rules/no-useless-computed-key"
32 enforceForClassMembers
: {
37 additionalProperties
: false
42 unnecessarilyComputedProperty
: "Unnecessarily computed property [{{property}}] found."
46 const sourceCode
= context
.getSourceCode();
47 const enforceForClassMembers
= context
.options
[0] && context
.options
[0].enforceForClassMembers
;
50 * Reports a given node if it violated this rule.
51 * @param {ASTNode} node The node to check.
54 function check(node
) {
60 nodeType
= typeof key
.value
;
64 if (node
.type
=== "MethodDefinition") {
65 allowedKey
= node
.static ? "prototype" : "constructor";
67 allowedKey
= "__proto__";
70 if (key
.type
=== "Literal" && (nodeType
=== "string" || nodeType
=== "number") && key
.value
!== allowedKey
) {
73 messageId
: "unnecessarilyComputedProperty",
74 data
: { property
: sourceCode
.getText(key
) },
76 const leftSquareBracket
= sourceCode
.getTokenBefore(key
, astUtils
.isOpeningBracketToken
);
77 const rightSquareBracket
= sourceCode
.getTokenAfter(key
, astUtils
.isClosingBracketToken
);
79 // If there are comments between the brackets and the property name, don't do a fix.
80 if (sourceCode
.commentsExistBetween(leftSquareBracket
, rightSquareBracket
)) {
84 const tokenBeforeLeftBracket
= sourceCode
.getTokenBefore(leftSquareBracket
);
86 // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
87 const needsSpaceBeforeKey
= tokenBeforeLeftBracket
.range
[1] === leftSquareBracket
.range
[0] &&
88 !astUtils
.canTokensBeAdjacent(tokenBeforeLeftBracket
, sourceCode
.getFirstToken(key
));
90 const replacementKey
= (needsSpaceBeforeKey
? " " : "") + key
.raw
;
92 return fixer
.replaceTextRange([leftSquareBracket
.range
[0], rightSquareBracket
.range
[1]], replacementKey
);
100 MethodDefinition
: enforceForClassMembers
? check
: lodash
.noop