Debian Codegraph @

lib/did_you_mean/spell_checker.rb

raw
1 # frozen-string-literal: true
2
3 require_relative "levenshtein"
4 require_relative "jaro_winkler"
5
6 module DidYouMean
7 class SpellChecker
8 def initialize(dictionary:)
9 @dictionary = dictionary
10 end
11
12 def correct(input)
13 normalized_input = normalize(input)
14 threshold = normalized_input.length > 3 ? 0.834 : 0.77
15
16 words = @dictionary.select { |word| JaroWinkler.distance(normalize(word), normalized_input) >= threshold }
17 words.reject! { |word| input.to_s == word.to_s }
18 words.sort_by! { |word| JaroWinkler.distance(word.to_s, normalized_input) }
19 words.reverse!
20
21 # Correct mistypes
22 threshold = (normalized_input.length * 0.25).ceil
23 corrections = words.select { |c| Levenshtein.distance(normalize(c), normalized_input) <= threshold }
24
25 # Correct misspells
26 if corrections.empty?
27 corrections = words.select do |word|
28 word = normalize(word)
29 length = normalized_input.length < word.length ? normalized_input.length : word.length
30
31 Levenshtein.distance(word, normalized_input) < length
32 end.first(1)
33 end
34
35 corrections
36 end
37
38 private
39
40 def normalize(str_or_symbol) #:nodoc:
41 str = str_or_symbol.to_s.downcase
42 str.tr!("@", "")
43 str
44 end
45 end
46 end