max-params.js 2.9 KB

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