UNPKG

1.86 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
3 * @author Josh Perez
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11var validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
12var keywords = require("../util/keywords");
13
14module.exports = function(context) {
15 var options = context.options[0] || {};
16 var allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords;
17
18 var allowPattern;
19 if (options.allowPattern) {
20 allowPattern = new RegExp(options.allowPattern);
21 }
22
23 return {
24 "MemberExpression": function(node) {
25 if (
26 node.computed &&
27 node.property.type === "Literal" &&
28 validIdentifier.test(node.property.value) &&
29 (allowKeywords || keywords.indexOf("" + node.property.value) === -1)
30 ) {
31 if (!(allowPattern && allowPattern.test(node.property.value))) {
32 context.report(node, "[" + JSON.stringify(node.property.value) + "] is better written in dot notation.");
33 }
34 }
35 if (
36 !allowKeywords &&
37 !node.computed &&
38 keywords.indexOf("" + node.property.name) !== -1
39 ) {
40 context.report(node, "." + node.property.name + " is a syntax error.");
41 }
42 }
43 };
44};
45
46module.exports.schema = [
47 {
48 "type": "object",
49 "properties": {
50 "allowKeywords": {
51 "type": "boolean"
52 },
53 "allowPattern": {
54 "type": "string"
55 }
56 },
57 "additionalProperties": false
58 }
59];