UNPKG

agentsqripts

Version:

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

65 lines (58 loc) 2.47 kB
/** * @file Levenshtein distance algorithm implementation for string similarity analysis * @description Single responsibility: Calculate edit distance between strings using dynamic programming * * This utility module implements the Levenshtein distance algorithm to measure string * similarity by calculating the minimum number of single-character edits (insertions, * deletions, substitutions) required to transform one string into another. It serves * as a fundamental component for code similarity detection, duplicate identification, * and fuzzy matching across the AgentSqripts analysis platform. * * Algorithm design rationale: * - Dynamic programming approach ensures O(m*n) time complexity for optimal performance * - Matrix-based calculation provides accurate edit distance measurement * - Null/empty string handling ensures robust operation with edge cases * - Single-function module maintains focus and testability * - Standard algorithm implementation enables predictable and reliable results * * Technical implementation: * - Matrix initialization establishes base cases for empty string transformations * - Character comparison optimizes for identical character sequences * - Three-operation minimum calculation (substitution, insertion, deletion) * - Bottom-up dynamic programming eliminates redundant calculations * - Final matrix position contains the complete edit distance result */ /** * Calculate Levenshtein distance between two strings * @param {string} str1 - First string * @param {string} str2 - Second string * @returns {number} Edit distance */ function levenshtein(str1, str2) { if (!str1 || !str2) return Math.max(str1?.length || 0, str2?.length || 0); const matrix = []; // Initialize the first column for (let i = 0; i <= str2.length; i++) { matrix[i] = [i]; } // Initialize the first row for (let j = 0; j <= str1.length; j++) { matrix[0][j] = j; } // Calculate distances for (let i = 1; i <= str2.length; i++) { for (let j = 1; j <= str1.length; j++) { if (str2.charAt(i - 1) === str1.charAt(j - 1)) { matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = Math.min( matrix[i - 1][j - 1] + 1, // substitution matrix[i][j - 1] + 1, // insertion matrix[i - 1][j] + 1 // deletion ); } } } return matrix[str2.length][str1.length]; } module.exports = levenshtein;