Javascript String Prototype Calculate Levenshtein Distance Between Two Strings

Description

Javascript String Prototype Calculate Levenshtein Distance Between Two Strings

function lev(string1, string2) { 
    let string1Length = string1.length, 
        string2Length = string2.length, 
        matrix = new Array(string1Length + 1); 
    for (let i = 0; i <= string1Length; i++) { 
        matrix[i] = new Array(string2Length + 1); 
        matrix[i][0] = i; //  w  w  w .j ava2  s.c  o m
    } 
    for (let i = 0; i <= string2Length; i++) { 
        matrix[0][i] = i; 
    } 

    for (let i = 1; i <= string1Length; i++) { 
        for (let n = 1; n <= string2Length; n++) { 
            let add = matrix[i - 1][n] + 1, 
                remove = matrix[i][n - 1] + 1, 
                 change = matrix[i - 1][n - 1] + Number(string1.charAt(i - 1) !== string2. 
                   charAt(n - 1)); 
            matrix[i][n] = Math.min(add, remove, change); 
        } 
    } 
    return matrix[string1Length][string2Length]; 
} 

console.log('Distance between pea and part is ' + lev('pea', 'part')); 
console.log('Distance between foo and four is ' + lev('foo', 'four')); 
console.log('Distance between matrix and mattress is ' + lev('matrix', 'mattress')); 
console.log('Distance between honey and money is ' + lev('honey', 'money')); 
console.log('Distance between tape and hate is ' + lev('tape', 'hate')); 



PreviousNext

Related