Debian Codegraph @

lib/did_you_mean/levenshtein.rb

raw
1 module DidYouMean
2 module Levenshtein # :nodoc:
3 # This code is based directly on the Text gem implementation
4 # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher.
5 #
6 # Returns a value representing the "cost" of transforming str1 into str2
7 def distance(str1, str2)
8 n = str1.length
9 m = str2.length
10 return m if n.zero?
11 return n if m.zero?
12
13 d = (0..m).to_a
14 x = nil
15
16 # to avoid duplicating an enumerable object, create it outside of the loop
17 str2_codepoints = str2.codepoints
18
19 str1.each_codepoint.with_index(1) do |char1, i|
20 j = 0
21 while j < m
22 cost = (char1 == str2_codepoints[j]) ? 0 : 1
23 x = min3(
24 d[j+1] + 1, # insertion
25 i + 1, # deletion
26 d[j] + cost # substitution
27 )
28 d[j] = i
29 i = x
30
31 j += 1
32 end
33 d[m] = x
34 end
35
36 x
37 end
38 module_function :distance
39
40 private
41
42 # detects the minimum value out of three arguments. This method is
43 # faster than `[a, b, c].min` and puts less GC pressure.
44 # See https://github.com/ruby/did_you_mean/pull/1 for a performance
45 # benchmark.
46 def min3(a, b, c)
47 if a < b && a < c
48 a
49 elsif b < c
50 b
51 else
52 c
53 end
54 end
55 module_function :min3
56 end
57 end