| 1 |
module DidYouMean |
| 2 |
module Jaro |
| 3 |
module_function |
| 4 |
|
| 5 |
def distance(str1, str2) |
| 6 |
str1, str2 = str2, str1 if str1.length > str2.length |
| 7 |
length1, length2 = str1.length, str2.length |
| 8 |
|
| 9 |
m = 0.0 |
| 10 |
t = 0.0 |
| 11 |
range = (length2 / 2).floor - 1 |
| 12 |
range = 0 if range < 0 |
| 13 |
flags1 = 0 |
| 14 |
flags2 = 0 |
| 15 |
|
| 16 |
# Avoid duplicating enumerable objects |
| 17 |
str1_codepoints = str1.codepoints |
| 18 |
str2_codepoints = str2.codepoints |
| 19 |
|
| 20 |
i = 0 |
| 21 |
while i < length1 |
| 22 |
last = i + range |
| 23 |
j = (i >= range) ? i - range : 0 |
| 24 |
|
| 25 |
while j <= last |
| 26 |
if flags2[j] == 0 && str1_codepoints[i] == str2_codepoints[j] |
| 27 |
flags2 |= (1 << j) |
| 28 |
flags1 |= (1 << i) |
| 29 |
m += 1 |
| 30 |
break |
| 31 |
end |
| 32 |
|
| 33 |
j += 1 |
| 34 |
end |
| 35 |
|
| 36 |
i += 1 |
| 37 |
end |
| 38 |
|
| 39 |
k = i = 0 |
| 40 |
while i < length1 |
| 41 |
if flags1[i] != 0 |
| 42 |
j = index = k |
| 43 |
|
| 44 |
k = while j < length2 |
| 45 |
index = j |
| 46 |
break(j + 1) if flags2[j] != 0 |
| 47 |
|
| 48 |
j += 1 |
| 49 |
end |
| 50 |
|
| 51 |
t += 1 if str1_codepoints[i] != str2_codepoints[index] |
| 52 |
end |
| 53 |
|
| 54 |
i += 1 |
| 55 |
end |
| 56 |
t = (t / 2).floor |
| 57 |
|
| 58 |
m == 0 ? 0 : (m / length1 + m / length2 + (m - t) / m) / 3 |
| 59 |
end |
| 60 |
end |
| 61 |
|
| 62 |
module JaroWinkler |
| 63 |
WEIGHT = 0.1 |
| 64 |
THRESHOLD = 0.7 |
| 65 |
|
| 66 |
module_function |
| 67 |
|
| 68 |
def distance(str1, str2) |
| 69 |
jaro_distance = Jaro.distance(str1, str2) |
| 70 |
|
| 71 |
if jaro_distance > THRESHOLD |
| 72 |
codepoints2 = str2.codepoints |
| 73 |
prefix_bonus = 0 |
| 74 |
|
| 75 |
i = 0 |
| 76 |
str1.each_codepoint do |char1| |
| 77 |
char1 == codepoints2[i] && i < 4 ? prefix_bonus += 1 : break |
| 78 |
i += 1 |
| 79 |
end |
| 80 |
|
| 81 |
jaro_distance + (prefix_bonus * WEIGHT * (1 - jaro_distance)) |
| 82 |
else |
| 83 |
jaro_distance |
| 84 |
end |
| 85 |
end |
| 86 |
end |
| 87 |
end |