UNPKG

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