From 08e130c79df9e81e6b4c9c0e0f8b52885ee20ada Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Sat, 20 Apr 2024 10:45:30 +1200 Subject: [PATCH] perf: don't collect more info than needed when resolving jest functions (#172) --- src/rules/utils/parseJestFnCall.ts | 36 +++++++++++------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/src/rules/utils/parseJestFnCall.ts b/src/rules/utils/parseJestFnCall.ts index a179645..38df6bd 100644 --- a/src/rules/utils/parseJestFnCall.ts +++ b/src/rules/utils/parseJestFnCall.ts @@ -499,11 +499,7 @@ 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(); - +const resolveScope = (scope: TSESLint.Scope.Scope, identifier: string) => { let currentScope: TSESLint.Scope.Scope | null = scope; while (currentScope !== null) { @@ -516,23 +512,19 @@ const collectReferences = (scope: TSESLint.Scope.Scope) => { const importDetails = describePossibleImportDef(def); - if (importDetails) { - imports.set(importDetails.local, importDetails); - - continue; + if (importDetails?.local === identifier) { + return importDetails; } - locals.add(ref.name); - } - - for (const ref of currentScope.through) { - unresolved.add(ref.identifier.name); + if (ref.name === identifier) { + return 'local'; + } } currentScope = currentScope.upper; } - return { locals, imports, unresolved }; + return null; }; interface ResolvedJestFn { @@ -545,9 +537,13 @@ const resolveToJestFn = ( context: TSESLint.RuleContext, identifier: string, ): ResolvedJestFn | null => { - const references = collectReferences(context.getScope()); + const maybeImport = resolveScope(context.getScope(), identifier); - const maybeImport = references.imports.get(identifier); + // the identifier was found as a local variable or function declaration + // meaning it's not a function from jest + if (maybeImport === 'local') { + return null; + } if (maybeImport) { // the identifier is imported from @jest/globals, @@ -563,12 +559,6 @@ const resolveToJestFn = ( return null; } - // the identifier was found as a local variable or function declaration - // meaning it's not a function from jest - if (references.locals.has(identifier)) { - return null; - } - return { original: resolvePossibleAliasedGlobal(identifier, context), local: identifier,