max-params.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 astUtils = require("./utils/ast-utils");
  10. const { upperCaseFirst } = require("../shared/string-utils");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. /** @type {import('../shared/types').Rule} */
  15. module.exports = {
  16. meta: {
  17. type: "suggestion",
  18. docs: {
  19. description: "Enforce a maximum number of parameters in function definitions",
  20. recommended: false,
  21. url: "https://eslint.org/docs/rules/max-params"
  22. },
  23. schema: [
  24. {
  25. oneOf: [
  26. {
  27. type: "integer",
  28. minimum: 0
  29. },
  30. {
  31. type: "object",
  32. properties: {
  33. maximum: {
  34. type: "integer",
  35. minimum: 0
  36. },
  37. max: {
  38. type: "integer",
  39. minimum: 0
  40. }
  41. },
  42. additionalProperties: false
  43. }
  44. ]
  45. }
  46. ],
  47. messages: {
  48. exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}."
  49. }
  50. },
  51. create(context) {
  52. const sourceCode = context.getSourceCode();
  53. const option = context.options[0];
  54. let numParams = 3;
  55. if (
  56. typeof option === "object" &&
  57. (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max"))
  58. ) {
  59. numParams = option.maximum || option.max;
  60. }
  61. if (typeof option === "number") {
  62. numParams = option;
  63. }
  64. /**
  65. * Checks a function to see if it has too many parameters.
  66. * @param {ASTNode} node The node to check.
  67. * @returns {void}
  68. * @private
  69. */
  70. function checkFunction(node) {
  71. if (node.params.length > numParams) {
  72. context.report({
  73. loc: astUtils.getFunctionHeadLoc(node, sourceCode),
  74. node,
  75. messageId: "exceed",
  76. data: {
  77. name: upperCaseFirst(astUtils.getFunctionNameWithKind(node)),
  78. count: node.params.length,
  79. max: numParams
  80. }
  81. });
  82. }
  83. }
  84. return {
  85. FunctionDeclaration: checkFunction,
  86. ArrowFunctionExpression: checkFunction,
  87. FunctionExpression: checkFunction
  88. };
  89. }
  90. };