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 //------------------------------------------------------------------------------
18 const MESSAGE_UNNECESSARY_COMPUTED = "Unnecessarily computed property [{{property}}] found.";
25 description: "disallow unnecessary computed property keys in objects and classes",
26 category: "ECMAScript 6",
28 url: "https://eslint.org/docs/rules/no-useless-computed-key"
34 enforceForClassMembers: {
39 additionalProperties: false
44 const sourceCode = context.getSourceCode();
45 const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers;
48 * Reports a given node if it violated this rule.
49 * @param {ASTNode} node The node to check.
52 function check(node) {
58 nodeType = typeof key.value;
62 if (node.type === "MethodDefinition") {
63 allowedKey = node.static ? "prototype" : "constructor";
65 allowedKey = "__proto__";
68 if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== allowedKey) {
71 message: MESSAGE_UNNECESSARY_COMPUTED,
72 data: { property: sourceCode.getText(key) },
74 const leftSquareBracket = sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken);
75 const rightSquareBracket = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken);
76 const tokensBetween = sourceCode.getTokensBetween(leftSquareBracket, rightSquareBracket, 1);
78 if (tokensBetween.slice(0, -1).some((token, index) =>
79 sourceCode.getText().slice(token.range[1], tokensBetween[index + 1].range[0]).trim())) {
81 // If there are comments between the brackets and the property name, don't do a fix.
85 const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket);
87 // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
88 const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] &&
89 !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
91 const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
93 return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
101 MethodDefinition: enforceForClassMembers ? check : lodash.noop