* Levenshtein distance algorithm implementation
(a: string, b: string)
| 224 | * Levenshtein distance algorithm implementation |
| 225 | */ |
| 226 | function levenshtein(a: string, b: string): number { |
| 227 | // Handle empty strings |
| 228 | if (a === "" || b === "") { |
| 229 | return Math.max(a.length, b.length) |
| 230 | } |
| 231 | const matrix = Array.from({ length: a.length + 1 }, (_, i) => |
| 232 | Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)), |
| 233 | ) |
| 234 | |
| 235 | for (let i = 1; i <= a.length; i++) { |
| 236 | for (let j = 1; j <= b.length; j++) { |
| 237 | const cost = a[i - 1] === b[j - 1] ? 0 : 1 |
| 238 | matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost) |
| 239 | } |
| 240 | } |
| 241 | return matrix[a.length][b.length] |
| 242 | } |
| 243 | |
| 244 | export const SimpleReplacer: Replacer = function* (_content, find) { |
| 245 | yield find |