1 | /**
|
2 | * @fileoverview Rule to flag when a function has too many parameters
|
3 | * @author Ilya Volodin
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | //------------------------------------------------------------------------------
|
9 | // Requirements
|
10 | //------------------------------------------------------------------------------
|
11 |
|
12 | const lodash = require("lodash");
|
13 |
|
14 | const astUtils = require("../ast-utils");
|
15 |
|
16 | //------------------------------------------------------------------------------
|
17 | // Rule Definition
|
18 | //------------------------------------------------------------------------------
|
19 |
|
20 | module.exports = {
|
21 | meta: {
|
22 | docs: {
|
23 | description: "enforce a maximum number of parameters in function definitions",
|
24 | category: "Stylistic Issues",
|
25 | recommended: false
|
26 | },
|
27 |
|
28 | schema: [
|
29 | {
|
30 | oneOf: [
|
31 | {
|
32 | type: "integer",
|
33 | minimum: 0
|
34 | },
|
35 | {
|
36 | type: "object",
|
37 | properties: {
|
38 | maximum: {
|
39 | type: "integer",
|
40 | minimum: 0
|
41 | },
|
42 | max: {
|
43 | type: "integer",
|
44 | minimum: 0
|
45 | }
|
46 | },
|
47 | additionalProperties: false
|
48 | }
|
49 | ]
|
50 | }
|
51 | ]
|
52 | },
|
53 |
|
54 | create(context) {
|
55 |
|
56 | const option = context.options[0];
|
57 | let numParams = 3;
|
58 |
|
59 | if (typeof option === "object" && option.hasOwnProperty("maximum") && typeof option.maximum === "number") {
|
60 | numParams = option.maximum;
|
61 | }
|
62 | if (typeof option === "object" && option.hasOwnProperty("max") && typeof option.max === "number") {
|
63 | numParams = option.max;
|
64 | }
|
65 | if (typeof option === "number") {
|
66 | numParams = option;
|
67 | }
|
68 |
|
69 | /**
|
70 | * Checks a function to see if it has too many parameters.
|
71 | * @param {ASTNode} node The node to check.
|
72 | * @returns {void}
|
73 | * @private
|
74 | */
|
75 | function checkFunction(node) {
|
76 | if (node.params.length > numParams) {
|
77 | context.report({
|
78 | node,
|
79 | message: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}.",
|
80 | data: {
|
81 | name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)),
|
82 | count: node.params.length,
|
83 | max: numParams
|
84 | }
|
85 | });
|
86 | }
|
87 | }
|
88 |
|
89 | return {
|
90 | FunctionDeclaration: checkFunction,
|
91 | ArrowFunctionExpression: checkFunction,
|
92 | FunctionExpression: checkFunction
|
93 | };
|
94 |
|
95 | }
|
96 | };
|