UNPKG

3.07 kBJavaScriptView Raw
1/**
2 * Requires space after opening square bracket and before closing.
3 * Reports on all on brackets, even on property accessors.
4 * Use [requireSpacesInsideArrayBrackets](http://jscs.info/rule/requireSpacesInsideArrayBrackets.html)
5 * to exclude property accessors.
6 *
7 * Types: `Boolean` or `Object`
8 *
9 * Values:
10 * - `Boolean`
11 * - `true`: strict mode
12 * - `Object`:
13 * - `"allExcept"`: Array specifying list of tokens that can occur after an opening square bracket or before a
14 * closing square bracket without a space
15
16 * #### Example
17 *
18 * ```js
19 * "requireSpacesInsideBrackets": true
20 * ```
21 * ```js
22 * "requireSpacesInsideBrackets": {
23 * "allExcept": [ "[", "]", "{", "}" ]
24 * }
25 * ```
26 *
27 * ##### Valid for mode `true`
28 *
29 * ```js
30 * var x = [ 1 ];
31 * var x = a[ 1 ];
32 * ```
33 *
34 * ##### Valid for mode `{ allExcept": [ "[", "]", "{", "}" ] }`
35 *
36 * ```js
37 * var x = [[ 1 ], [ 2 ]];
38 * var x = [{ a: 1 }, { b: 2}];
39 * ```
40 *
41 * ##### Invalid
42 *
43 * ```js
44 * var x = [1];
45 * ```
46 */
47
48var assert = require('assert');
49
50module.exports = function() {};
51
52module.exports.prototype = {
53
54 configure: function(value) {
55 var isObject = typeof value === 'object';
56
57 var error = this.getOptionName() + ' rule requires string value true or object';
58
59 if (isObject) {
60 assert('allExcept' in value, error);
61 } else {
62 assert(value === true, error);
63 }
64
65 this._exceptions = {};
66
67 if (isObject) {
68 (value.allExcept || []).forEach(function(value) {
69 this._exceptions[value] = true;
70 }, this);
71 }
72 },
73
74 getOptionName: function() {
75 return 'requireSpacesInsideBrackets';
76 },
77
78 check: function(file, errors) {
79 var exceptions = this._exceptions;
80
81 file.iterateTokensByTypeAndValue('Punctuator', '[', function(token) {
82 var nextToken = file.getNextToken(token, { includeComments: true });
83 var value = nextToken.value;
84
85 if (value in exceptions) {
86 return;
87 }
88
89 // Skip for empty array brackets
90 if (value === ']') {
91 return;
92 }
93
94 errors.assert.spacesBetween({
95 token: token,
96 nextToken: nextToken,
97 exactly: 1,
98 message: 'One space required after opening bracket'
99 });
100 });
101
102 file.iterateTokensByTypeAndValue('Punctuator', ']', function(token) {
103 var prevToken = file.getPrevToken(token, { includeComments: true });
104 var value = prevToken.value;
105
106 if (value in exceptions) {
107 return;
108 }
109
110 // Skip for empty array brackets
111 if (value === '[') {
112 return;
113 }
114
115 errors.assert.spacesBetween({
116 token: prevToken,
117 nextToken: token,
118 exactly: 1,
119 message: 'One space required before closing bracket'
120 });
121 });
122 }
123};