UNPKG

3.42 kBJavaScriptView Raw
1/**
2 * Enable validation of separators between function parameters. Will ignore newlines.
3 *
4 * Type: `String`
5 *
6 * Values:
7 *
8 * - `","`: function parameters are immediately followed by a comma
9 * - `", "`: function parameters are immediately followed by a comma and then a space
10 * - `" ,"`: function parameters are immediately followed by a space and then a comma
11 * - `" , "`: function parameters are immediately followed by a space, a comma, and then a space
12 *
13 * #### Example
14 *
15 * ```js
16 * "validateParameterSeparator": ", "
17 * ```
18 *
19 * ##### Valid
20 *
21 * ```js
22 * function a(b, c) {}
23 * ```
24 *
25 * ##### Invalid
26 *
27 * ```js
28 * function a(b , c) {}
29 * ```
30 */
31
32var assert = require('assert');
33
34module.exports = function() {};
35
36module.exports.prototype = {
37
38 configure: function(options) {
39 assert(
40 typeof options === 'string' && /^[ ]?,[ ]?$/.test(options),
41 this.getOptionName() + ' option requires string value containing only a comma and optional spaces'
42 );
43
44 this._separator = options;
45 },
46
47 getOptionName: function() {
48 return 'validateParameterSeparator';
49 },
50
51 check: function(file, errors) {
52
53 var separators = this._separator.split(',');
54 var whitespaceBeforeComma = Boolean(separators.shift());
55 var whitespaceAfterComma = Boolean(separators.pop());
56
57 file.iterateNodesByType([
58 'FunctionDeclaration',
59 'FunctionExpression',
60 'ClassMethod'
61 ], function(node) {
62
63 node.params.forEach(function(paramNode) {
64
65 var prevParamToken = file.getFirstNodeToken(paramNode);
66 var punctuatorToken = file.getNextToken(prevParamToken);
67
68 if (punctuatorToken.value === ',') {
69
70 if (whitespaceBeforeComma) {
71 errors.assert.spacesBetween({
72 token: prevParamToken,
73 nextToken: punctuatorToken,
74 exactly: 1,
75 message: 'One space required after function parameter \'' + prevParamToken.value + '\''
76 });
77 } else {
78 errors.assert.noWhitespaceBetween({
79 token: prevParamToken,
80 nextToken: punctuatorToken,
81 message: 'Unexpected space after function parameter \'' + prevParamToken.value + '\''
82 });
83 }
84
85 var nextParamToken = file.getNextToken(punctuatorToken);
86
87 if (whitespaceAfterComma) {
88 errors.assert.spacesBetween({
89 token: punctuatorToken,
90 nextToken: nextParamToken,
91 exactly: 1,
92 message: 'One space required before function parameter \'' + nextParamToken.value + '\''
93 });
94 } else {
95 errors.assert.noWhitespaceBetween({
96 token: punctuatorToken,
97 nextToken: nextParamToken,
98 message: 'Unexpected space before function parameter \'' + nextParamToken.value + '\''
99 });
100 }
101 }
102 });
103 });
104 }
105
106};