Last active
September 29, 2015 15:08
-
-
Save sts/1620125 to your computer and use it in GitHub Desktop.
Javascript Implementation of Levenshtein's Distance Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* (c) 2012, Stefan Schlesinger - http://sts.ono.at | |
* | |
* My first version of a Javascript Levenshtein distance implementation. | |
* http://en.wikipedia.org/wiki/Levenshtein_distance | |
*/ | |
function unpack(str) { | |
var bytes = []; | |
for(var i = 0; i < str.length; i++) { | |
var char = str.charCodeAt(i); | |
bytes.push(char & 0xFF); | |
} | |
return bytes; | |
} | |
function distance(str1, str2) { | |
var s = unpack(str1); | |
var t = unpack(str2); | |
var n = s.length; | |
var m = t.length; | |
if (n == 0) return m; | |
if (m == 0) return n; | |
# this array should be different | |
var d = [0, 1, 2, 3]; | |
var x; | |
for( var i=0; i<n; i++ ) { | |
var e = i+1; | |
for( var j=0; j<m; j++) { | |
var cost = (s[i] == t[j]) ? 0 : 1; | |
var x = Math.min( | |
d[j+1] + 1, | |
e + 1, | |
d[j] + cost | |
); | |
d[j] = e; | |
e = x; | |
} | |
d[m] = x; | |
} | |
return x; | |
} | |
distance('hello', 'ehllo'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment