diff --git a/tools/eslint-rules/no-duplicate-requires.js b/tools/eslint-rules/no-duplicate-requires.js index 0a73ccb44a0678..1d81cb7f37b58b 100644 --- a/tools/eslint-rules/no-duplicate-requires.js +++ b/tools/eslint-rules/no-duplicate-requires.js @@ -1,6 +1,7 @@ /** * @fileoverview Ensure modules are not required twice at top level of a module * @author devsnek + * @author RedYetiDev */ 'use strict'; @@ -10,20 +11,18 @@ const { isRequireCall, isString } = require('./rules-utils.js'); // Rule Definition //------------------------------------------------------------------------------ -const secondLevelTypes = [ +const topLevelTypes = new Set([ 'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression', 'ClassBody', 'MethodDefinition', -]; +]); -function isTopLevel(node) { - while (!secondLevelTypes.includes(node.type)) { +const isTopLevel = (node) => { + while (node) { + if (topLevelTypes.has(node.type)) return false; node = node.parent; - if (!node) { - return true; - } } - return false; -} + return true; +}; module.exports = { create(context) { @@ -31,37 +30,25 @@ module.exports = { return {}; } - function getRequiredModuleNameFromCall(node) { - // Node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - return node.arguments[0].value.trim(); - } - - return undefined; - } + const requiredModules = new Set(); - const required = new Set(); - - const rules = { - CallExpression: (node) => { + return { + CallExpression(node) { if (isRequireCall(node) && isTopLevel(node)) { - const moduleName = getRequiredModuleNameFromCall(node); - if (moduleName === undefined) { - return; - } - if (required.has(moduleName)) { - context.report( - node, - '\'{{moduleName}}\' require is duplicated.', - { moduleName }, - ); - } else { - required.add(moduleName); + const [firstArg] = node.arguments; + if (isString(firstArg)) { + const moduleName = firstArg.value.trim(); + if (requiredModules.has(moduleName)) { + context.report({ + node, + message: `'${moduleName}' require is duplicated.`, + }); + } else { + requiredModules.add(moduleName); + } } } }, }; - - return rules; }, };