agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
71 lines (62 loc) • 2.18 kB
JavaScript
/**
* @file JSON in loop detector
* @description Detects JSON operations in loops or hot paths
*/
/**
* Detects JSON operations in loops or hot paths
* @param {string} content - File content
* @param {string} filePath - Path to the file
* @returns {Array} Array of JSON performance issues
*/
function detectJSONInLoops(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*\(|\.filter\s*\(|\.reduce\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;
}
}
// Only flag JSON operations that are actually inside loops
if ((line.includes('JSON.stringify') || line.includes('JSON.parse')) && insideLoop) {
const pattern = PERFORMANCE_PATTERNS['json_in_loop'];
const operation = line.includes('JSON.stringify') ? 'stringify' : 'parse';
issues.push({
type: 'json_in_loop',
severity: pattern.severity,
category: pattern.category,
location: `${filePath}:${lineNumber}`,
line: lineNumber,
code: line.trim(),
operation: operation,
description: `Repeated JSON ${operation} detected in hot path`,
summary: `Repeated JSON ${operation} detected in hot path`,
recommendation: 'Cache serialized payload outside loop/request if static, or use streaming parser',
effort: pattern.effort,
impact: pattern.impact,
estimatedSavings: '10-30% CPU gain per request'
});
}
});
return issues;
}
module.exports = {
detectJSONInLoops
};