agentsqripts
Version:
Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems
58 lines (51 loc) • 2 kB
JavaScript
/**
* @file Detect space complexity patterns
* @description Single responsibility: Identify patterns with high space complexity
*/
const { iterateLines } = require('../../../utils/patternDetector');
/**
* Detect space complexity patterns
*/
function detectSpaceComplexity(lines, filePath) {
const issues = [];
iterateLines(lines, (line, lineNumber, trimmed, i) => {
// O(n) space patterns - creating arrays/objects proportional to input
if (/new Array\s*\(\s*\w+\.length\s*\)|Array\(.*\.length\)/.test(trimmed)) {
issues.push({
type: 'linear_space',
severity: 'MEDIUM',
category: 'Memory',
location: `${filePath}:${lineNumber}`,
line: lineNumber,
code: trimmed,
description: 'Creating array proportional to input size - O(n) space complexity',
summary: 'Linear space complexity pattern',
recommendation: 'Consider if constant space algorithm is possible',
effort: 3,
impact: 'Reduces memory usage for large inputs',
estimatedSavings: 'O(n) to O(1) space reduction possible'
});
}
// Nested data structures - potential O(n²) space
const nestedPattern = /\[\s*\]|\{\s*\}/g;
const nestingDepth = (trimmed.match(nestedPattern) || []).length;
if (nestingDepth > 2 && /for\s*\(|\.map\s*\(/.test(trimmed)) {
issues.push({
type: 'nested_space',
severity: 'HIGH',
category: 'Memory',
location: `${filePath}:${lineNumber}`,
line: lineNumber,
code: trimmed,
description: `Deep nesting in loop - potential O(n²) space complexity`,
summary: 'Nested data structure space complexity',
recommendation: 'Flatten data structures or use references',
effort: 4,
impact: 'Significant memory reduction for nested data',
estimatedSavings: 'O(n²) to O(n) space reduction'
});
}
});
return issues;
}
module.exports = detectSpaceComplexity;