Created
October 17, 2012 19:13
-
-
Save supernullset/3907497 to your computer and use it in GitHub Desktop.
Fuzzy string comparison/sort in javascript
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
curry = (fn)-> | |
slice = Array.prototype.slice | |
args = slice.apply arguments, [1] | |
return -> | |
fn.apply null, args.concat(slice.apply arguments) | |
levenshteinD = (s,t) -> | |
if !s.length then return t.length | |
if !t.length then return s.length | |
return Math.min( | |
levenshteinD(s.substr(1), t) + 1, | |
levenshteinD(t.substr(1), s) + 1, | |
levenshteinD(s.substr(1), t.substr(1)) + (if s[0] is not t[0] then 1 else 0) | |
) | |
levenshteinS = (a,b)-> | |
A = a[1] | |
B = b[1] | |
if A < B | |
-1 | |
else if A == B | |
0 | |
else | |
1 | |
rank_strings = (origin,strA) -> | |
levenshteinC = curry(levenshteinD, origin) | |
ranking = strA.map(levenshteinC) | |
values = [] | |
for i in [0..(ranking.length-1)] | |
values[i]=[strA[i],ranking[i]] | |
values.sort(levenshteinS).map((a)-> return a[0]) | |
strings = ["cat", "house", "pearls of wis", "hello my name is"] | |
origin = "cat" | |
console.log rank_strings origin,strings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment