Module: String::Quicksilver

Defined in:
lib/string_scorer/scorers/quicksilver.rb

Overview

Algorithm from is.gd/CUqC

Class Method Summary collapse

Class Method Details

.score(string, abbreviation, offset = 0) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/string_scorer/scorers/quicksilver.rb', line 9

def score(string, abbreviation, offset = 0)
  length = abbreviation.length

  return 0.9 if length == 0
  return 0.0 if length > string.length

  abbreviation.length.downto(1) do |i|
    sub   = abbreviation[0,i]
    index = string.index(sub)

    next if index.nil?
    next if index + length > string.length + offset

    next_string       = string[(index+sub.length)..-1]
    next_abbreviation = (i >= abbreviation.length) ? '' : abbreviation[i..-1]

    remaining_score   = score(string, next_abbreviation, offset + index)

    if remaining_score > 0
      score = string.length - next_string.length

      if index != 0
        c = string[index-1]

        if (c==32 || c == 9)     # space or tab
          (index-2).downto(0) do |j|
            c = string[j]
            score -= ((c == 32 || c == 9) ? 1 : 0.15)
          end
        elsif c >= 65 && c <= 90 # capital letter
          (index-1).downto(0) do |j|
            c = string[j]
            score -= (c >= 65 && c <= 90 ? 1 : 0.15)
          end
        else
          score -= index
        end
      end

      score += remaining_score * next_string.length
      score /= string.length
      return score
    end
  end

  0.0
end