UNPKG

2.7 kBJavaScriptView Raw
1/**
2 * Require space after colon in object destructuring.
3 *
4 * Type: `Boolean`
5 *
6 * Value: `true`
7 *
8 * Version: `ES6`
9 *
10 * #### Example
11 *
12 * ```js
13 * "requireSpaceBeforeDestructuredValues": true
14 * ```
15 *
16 * ##### Valid
17 * ```js
18 * const { foo: objectsFoo } = SomeObject;
19 * ```
20 * ##### Invalid
21 * ```js
22 * const { foo:objectsFoo } = SomeObject;
23 * ```
24 *
25 * ##### Valid
26 * ```js
27 * const { [ { foo: objectsFoo } ] } = SomeObject;
28 * ```
29 * ##### Invalid
30 * ```js
31 * const { [ { foo:objectsFoo } ] } = SomeObject;
32 * ```
33 */
34
35var assert = require('assert');
36
37module.exports = function() {};
38
39module.exports.prototype = {
40
41 configure: function(options) {
42 assert(
43 options === true,
44 this.getOptionName() + ' option requires a true value or should be removed'
45 );
46 },
47
48 getOptionName: function() {
49 return 'requireSpaceBeforeDestructuredValues';
50 },
51
52 check: function(file, errors) {
53 var checkSpaceMissing = function(propKey) {
54 var keyToken = file.getFirstNodeToken(propKey);
55 var colon = file.findNextToken(keyToken, 'Punctuator', ':');
56
57 errors.assert.whitespaceBetween({
58 token: colon,
59 nextToken: file.getNextToken(colon),
60 message: 'Missing space after key colon'
61 });
62 };
63
64 var letsCheckThisOne = function(item) {
65
66 if (!item) {
67 return;
68 }
69
70 if (item.type === 'ObjectPattern') {
71 item.properties.forEach(function(property) {
72
73 if (property.shorthand || property.method) {
74 return;
75 }
76
77 checkSpaceMissing(property.key);
78
79 //Strategy for nested structures
80 var propValue = property.value;
81
82 if (!propValue) {
83 return;
84 }
85
86 letsCheckThisOne(propValue);
87 });
88 }
89
90 if (item.type === 'ArrayPattern') {
91 item.elements.forEach(letsCheckThisOne);
92 }
93 };
94
95 file.iterateNodesByType(['VariableDeclaration', 'AssignmentExpression'], function(node) {
96
97 if (node.type === 'VariableDeclaration') {
98 node.declarations.forEach(function(declaration) {
99 letsCheckThisOne(declaration.id || {});
100 });
101 }
102
103 if (node.type === 'AssignmentExpression') {
104 var left = node.left;
105
106 if (left) {
107 letsCheckThisOne(left);
108 }
109 }
110 });
111 }
112};