UNPKG

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