From 6f85b64856bc5b5524aef9b9215916adaeef68e1 Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Sat, 5 Nov 2022 10:55:10 +1300 Subject: [PATCH] refactor: inline `collectReferences` utility into `scopeHasLocalReference` (#1276) * refactor: inline `collectReferences` utility into `scopeHasLocalReference` * refactor: optimize a little further * refactor: remove unneeded checks --- src/rules/utils/parseJestFnCall.ts | 72 +++++++++++------------------- 1 file changed, 25 insertions(+), 47 deletions(-) diff --git a/src/rules/utils/parseJestFnCall.ts b/src/rules/utils/parseJestFnCall.ts index 64905f95e..0430b29d7 100644 --- a/src/rules/utils/parseJestFnCall.ts +++ b/src/rules/utils/parseJestFnCall.ts @@ -514,42 +514,6 @@ const describePossibleImportDef = (def: TSESLint.Scope.Definition) => { return null; }; -const collectReferences = (scope: TSESLint.Scope.Scope) => { - const locals = new Set(); - const imports = new Map(); - const unresolved = new Set(); - - let currentScope: TSESLint.Scope.Scope | null = scope; - - while (currentScope !== null) { - for (const ref of currentScope.variables) { - if (ref.defs.length === 0) { - continue; - } - - const def = ref.defs[ref.defs.length - 1]; - - const importDetails = describePossibleImportDef(def); - - if (importDetails) { - imports.set(importDetails.local, importDetails); - - continue; - } - - locals.add(ref.name); - } - - for (const ref of currentScope.through) { - unresolved.add(ref.identifier.name); - } - - currentScope = currentScope.upper; - } - - return { locals, imports, unresolved }; -}; - const resolveScope = (scope: TSESLint.Scope.Scope, identifier: string) => { let currentScope: TSESLint.Scope.Scope | null = scope; @@ -621,15 +585,29 @@ export const scopeHasLocalReference = ( scope: TSESLint.Scope.Scope, referenceName: string, ) => { - const references = collectReferences(scope); - - return ( - // referenceName was found as a local variable or function declaration. - references.locals.has(referenceName) || - // referenceName was found as an imported identifier - references.imports.has(referenceName) || - // referenceName was not found as an unresolved reference, - // meaning it is likely not an implicit global reference. - !references.unresolved.has(referenceName) - ); + let currentScope: TSESLint.Scope.Scope | null = scope; + + while (currentScope !== null) { + for (const ref of currentScope.variables) { + if (ref.defs.length === 0) { + continue; + } + + const def = ref.defs[ref.defs.length - 1]; + + const importDetails = describePossibleImportDef(def); + + // referenceName was found as an imported identifier + if (importDetails?.local === referenceName) { + return true; + } + + // referenceName was found as a local variable or function declaration. + return ref.name === referenceName; + } + + currentScope = currentScope.upper; + } + + return false; };