UNPKG

3.27 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow unnecessary computed property keys in object literals
3 * @author Burak Yigit Kaya
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const astUtils = require("../util/ast-utils");
12
13//------------------------------------------------------------------------------
14// Rule Definition
15//------------------------------------------------------------------------------
16
17const MESSAGE_UNNECESSARY_COMPUTED = "Unnecessarily computed property [{{property}}] found.";
18
19module.exports = {
20 meta: {
21 type: "suggestion",
22
23 docs: {
24 description: "disallow unnecessary computed property keys in object literals",
25 category: "ECMAScript 6",
26 recommended: false,
27 url: "https://eslint.org/docs/rules/no-useless-computed-key"
28 },
29
30 schema: [],
31 fixable: "code"
32 },
33 create(context) {
34 const sourceCode = context.getSourceCode();
35
36 return {
37 Property(node) {
38 if (!node.computed) {
39 return;
40 }
41
42 const key = node.key,
43 nodeType = typeof key.value;
44
45 if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== "__proto__") {
46 context.report({
47 node,
48 message: MESSAGE_UNNECESSARY_COMPUTED,
49 data: { property: sourceCode.getText(key) },
50 fix(fixer) {
51 const leftSquareBracket = sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken);
52 const rightSquareBracket = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken);
53 const tokensBetween = sourceCode.getTokensBetween(leftSquareBracket, rightSquareBracket, 1);
54
55 if (tokensBetween.slice(0, -1).some((token, index) =>
56 sourceCode.getText().slice(token.range[1], tokensBetween[index + 1].range[0]).trim())) {
57
58 // If there are comments between the brackets and the property name, don't do a fix.
59 return null;
60 }
61
62 const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket);
63
64 // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
65 const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] &&
66 !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
67
68 const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
69
70 return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
71 }
72 });
73 }
74 }
75 };
76 }
77};