From e4a567434d84585e01efcdd22ca7e77288069ae5 Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Sat, 5 Nov 2022 09:32:51 +1300 Subject: [PATCH] perf: don't collect more info than needed when resolving jest functions (#1275) --- src/rules/utils/parseJestFnCall.ts | 42 ++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/src/rules/utils/parseJestFnCall.ts b/src/rules/utils/parseJestFnCall.ts index 0c75211ab..64905f95e 100644 --- a/src/rules/utils/parseJestFnCall.ts +++ b/src/rules/utils/parseJestFnCall.ts @@ -550,6 +550,34 @@ const collectReferences = (scope: TSESLint.Scope.Scope) => { return { locals, imports, unresolved }; }; +const resolveScope = (scope: TSESLint.Scope.Scope, identifier: string) => { + 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?.local === identifier) { + return importDetails; + } + + if (ref.name === identifier) { + return 'local'; + } + } + + currentScope = currentScope.upper; + } + + return null; +}; + interface ResolvedJestFn { original: string | null; local: string; @@ -560,9 +588,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, @@ -578,12 +610,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,