no-dupe-args.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @fileoverview Rule to flag duplicate arguments
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "problem",
  12. docs: {
  13. description: "disallow duplicate arguments in `function` definitions",
  14. category: "Possible Errors",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-dupe-args"
  17. },
  18. schema: [],
  19. messages: {
  20. unexpected: "Duplicate param '{{name}}'."
  21. }
  22. },
  23. create(context) {
  24. //--------------------------------------------------------------------------
  25. // Helpers
  26. //--------------------------------------------------------------------------
  27. /**
  28. * Checks whether or not a given definition is a parameter's.
  29. * @param {eslint-scope.DefEntry} def A definition to check.
  30. * @returns {boolean} `true` if the definition is a parameter's.
  31. */
  32. function isParameter(def) {
  33. return def.type === "Parameter";
  34. }
  35. /**
  36. * Determines if a given node has duplicate parameters.
  37. * @param {ASTNode} node The node to check.
  38. * @returns {void}
  39. * @private
  40. */
  41. function checkParams(node) {
  42. const variables = context.getDeclaredVariables(node);
  43. for (let i = 0; i < variables.length; ++i) {
  44. const variable = variables[i];
  45. // Checks and reports duplications.
  46. const defs = variable.defs.filter(isParameter);
  47. if (defs.length >= 2) {
  48. context.report({
  49. node,
  50. messageId: "unexpected",
  51. data: { name: variable.name }
  52. });
  53. }
  54. }
  55. }
  56. //--------------------------------------------------------------------------
  57. // Public API
  58. //--------------------------------------------------------------------------
  59. return {
  60. FunctionDeclaration: checkParams,
  61. FunctionExpression: checkParams
  62. };
  63. }
  64. };