summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/dot-notation.js
blob: a8a64a280c594c8a759415fa87301f1945c836f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
 * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
 * @author Josh Perez
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
const keywords = require("../util/keywords");

module.exports = {
    meta: {
        docs: {
            description: "enforce dot notation whenever possible",
            category: "Best Practices",
            recommended: false
        },

        schema: [
            {
                type: "object",
                properties: {
                    allowKeywords: {
                        type: "boolean"
                    },
                    allowPattern: {
                        type: "string"
                    }
                },
                additionalProperties: false
            }
        ]
    },

    create(context) {
        const options = context.options[0] || {};
        const allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords;

        let allowPattern;

        if (options.allowPattern) {
            allowPattern = new RegExp(options.allowPattern);
        }

        return {
            MemberExpression(node) {
                if (
                    node.computed &&
                    node.property.type === "Literal" &&
                    validIdentifier.test(node.property.value) &&
                    (allowKeywords || keywords.indexOf("" + node.property.value) === -1)
                ) {
                    if (!(allowPattern && allowPattern.test(node.property.value))) {
                        context.report(node.property, "[" + JSON.stringify(node.property.value) + "] is better written in dot notation.");
                    }
                }
                if (
                    !allowKeywords &&
                    !node.computed &&
                    keywords.indexOf("" + node.property.name) !== -1
                ) {
                    context.report(node.property, "." + node.property.name + " is a syntax error.");
                }
            }
        };
    }
};