2 * @fileoverview Rule to disallow unnecessary computed property keys in object literals
3 * @author Burak Yigit Kaya
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils = require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
22 description: "disallow unnecessary computed property keys in objects and classes",
23 category: "ECMAScript 6",
25 url: "https://eslint.org/docs/rules/no-useless-computed-key"
31 enforceForClassMembers: {
36 additionalProperties: false
41 unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found."
45 const sourceCode = context.getSourceCode();
46 const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers;
49 * Reports a given node if it violated this rule.
50 * @param {ASTNode} node The node to check.
53 function check(node) {
59 nodeType = typeof key.value;
63 if (node.type === "MethodDefinition") {
64 allowedKey = node.static ? "prototype" : "constructor";
66 allowedKey = "__proto__";
69 if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== allowedKey) {
72 messageId: "unnecessarilyComputedProperty",
73 data: { property: sourceCode.getText(key) },
75 const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken);
76 const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken);
78 // If there are comments between the brackets and the property name, don't do a fix.
79 if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) {
83 const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket);
85 // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
86 const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] &&
87 !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
89 const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
91 return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
98 * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`.
106 MethodDefinition: enforceForClassMembers ? check : noop