UNPKG

agentsqripts

Version:

Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems

85 lines (73 loc) 2.45 kB
/** * @file Promise in loop detector * @description Detects promise creation inside loops */ /** * Detects promise creation in loops * @param {string} content - File content * @param {string} filePath - Path to the file * @returns {Array} Array of promise in loop issues */ function detectPromiseInLoops(content, filePath) { const issues = []; const lines = content.split('\n'); const { PERFORMANCE_PATTERNS } = require('./performancePatterns'); let insideLoop = false; let loopDepth = 0; let loopStartLine = 0; lines.forEach((line, index) => { const lineNumber = index + 1; const trimmedLine = line.trim(); // Track if we're inside a loop if (/for\s*\(|while\s*\(|\.forEach\s*\(|\.map\s*\(/.test(trimmedLine)) { if (!insideLoop) { loopStartLine = lineNumber; } insideLoop = true; loopDepth++; } // Track loop end if (trimmedLine.includes('}') || trimmedLine.includes('});')) { loopDepth--; if (loopDepth <= 0) { insideLoop = false; loopDepth = 0; } } // Detect promise creation inside loops if (insideLoop) { const promisePatterns = [ /new\s+Promise\s*\(/, /Promise\.resolve\s*\(/, /Promise\.reject\s*\(/, /fetch\s*\(/, /axios\.[a-z]+\s*\(/, /\.then\s*\(/ ]; const hasPromise = promisePatterns.some(pattern => pattern.test(line)); // Check if it's already using Promise.all or similar const hasPromiseAll = /Promise\.(all|allSettled|race)\s*\(/.test(line); if (hasPromise && !hasPromiseAll) { const pattern = PERFORMANCE_PATTERNS['promise_in_loop']; issues.push({ type: 'promise_in_loop', severity: pattern.severity, category: pattern.category, location: `${filePath}:${lineNumber}`, line: lineNumber, code: line.trim(), description: 'Creating promises in loop can cause memory and performance issues', summary: 'Promise creation inside loop', recommendation: 'Collect promises in array and use Promise.all() for concurrent execution', effort: pattern.effort, impact: pattern.impact, estimatedSavings: '30-50% memory and performance improvement' }); } } }); return issues; } module.exports = { detectPromiseInLoops };