UNPKG

2.06 kBJavaScriptView Raw
1/**
2 * Disallows parentheses around arrow function expressions with a single parameter.
3 *
4 * Type: `Boolean`
5 *
6 * Value: `true`
7 *
8 * Version: `ES6`
9 *
10 * #### Example
11 *
12 * ```js
13 * "disallowParenthesesAroundArrowParam": true
14 * ```
15 *
16 * ##### Valid
17 *
18 * ```js
19 * [1, 2, 3].map(x => x * x);
20 * // parentheses are always required for multiple parameters
21 * [1, 2, 3].map((x, y, z) => x * x);
22 * ```
23 *
24 * ##### Invalid
25 *
26 * ```js
27 * [1, 2, 3].map((x) => x * x);
28 * ```
29 */
30
31var assert = require('assert');
32
33module.exports = function() {};
34
35module.exports.prototype = {
36
37 configure: function(options) {
38 assert(
39 options === true,
40 this.getOptionName() + ' option requires a true value or should be removed'
41 );
42 },
43
44 getOptionName: function() {
45 return 'disallowParenthesesAroundArrowParam';
46 },
47
48 check: function(file, errors) {
49 function isWrapped(node) {
50 var openParensToken = file.getPrevToken(file.getFirstNodeToken(node));
51 var closingParensToken = file.getNextToken(file.getLastNodeToken(node));
52 var closingTokenValue = closingParensToken ? closingParensToken.value : '';
53
54 return openParensToken.value + closingTokenValue === '()';
55 }
56
57 file.iterateNodesByType('ArrowFunctionExpression', function(node) {
58 if (node.params.length !== 1) {
59 return;
60 }
61 var firstParam = node.params[0];
62
63 var hasDefaultParameter = firstParam.type === 'AssignmentPattern';
64 var hasDestructuring = firstParam.type === 'ObjectPattern' || firstParam.type === 'ArrayPattern';
65 var hasRestElement = firstParam.type === 'RestElement';
66
67 if (hasDefaultParameter ||
68 hasDestructuring ||
69 hasRestElement) {
70 return;
71 }
72
73 if (isWrapped(firstParam)) {
74 errors.add('Illegal wrap of arrow function expressions in parentheses', firstParam);
75 }
76 });
77 }
78
79};