1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| const levenshteinDistance = (str1: string, str2: string) => { const len1 = str1.length; const len2 = str2.length;
const matrix: Array<number[]> = [];
for (let i = 0; i <= len1; i++) { matrix[i] = [i]; }
for (let j = 0; j <= len2; j++) { matrix[0][j] = j; }
for (let i = 1; i <= len1; i++) { for (let j = 1; j <= len2; j++) { const cost = str1[i - 1] === str2[j - 1] ? 0 : 1; matrix[i][j] = Math.min( matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost ); } }
return matrix[len1][len2]; } export const similarity = (str1: string, str2: string) => { const distance = levenshteinDistance(str1, str2); const maxLength = Math.max(str1.length, str2.length); return 1 - distance / maxLength; }
|