UNPKG

1.94 kBJavaScriptView Raw
1/**
2 * Requires variable declarations from objects via destructuring
3 *
4 * Type: `Boolean`
5 *
6 * Value: `true`
7 *
8 * Version: `ES6`
9 *
10 * #### Example
11 *
12 * ```js
13 * "requireObjectDestructuring": true
14 * ```
15 *
16 * ##### Valid
17 *
18 * ```js
19 * var { foo } = SomeThing;
20 * var { bar } = SomeThing.foo;
21 * var { val } = SomeThing['some.key'];
22 * ```
23 *
24 * ##### Invalid
25 *
26 * ```js
27 * var foo = SomeThing.foo;
28 * var bar = SomeThing.foo.bar;
29 * var val = SomeThing['some.key'].val;
30 * ```
31 */
32
33var assert = require('assert');
34
35module.exports = function() {};
36
37module.exports.prototype = {
38 configure: function(option) {
39 var isTrue = option === true;
40
41 assert(
42 isTrue || (typeof option === 'object' && Array.isArray(option.allExcept)),
43 this.getOptionName() + ' requires the value `true` ' +
44 'or an object with an `allExcept` array property'
45 );
46
47 this._propertyExceptions = !isTrue && option.allExcept || [];
48 },
49
50 getOptionName: function() {
51 return 'requireObjectDestructuring';
52 },
53
54 check: function(file, errors) {
55 var propertyExceptions = this._propertyExceptions;
56
57 file.iterateNodesByType('VariableDeclaration', function(node) {
58
59 node.declarations.forEach(function(declaration) {
60 var declarationId = declaration.id || {};
61 var declarationInit = declaration.init || {};
62
63 if (declarationId.type !== 'Identifier' || declarationInit.type !== 'MemberExpression') {
64 return;
65 }
66
67 var propertyName = declarationInit.property && declarationInit.property.name;
68
69 if (declarationId.name === propertyName &&
70 propertyExceptions.indexOf(propertyName) < 0) {
71
72 errors.add('Property assignments should use destructuring', node);
73 }
74 });
75 });
76 }
77};