Skip to content

Commit ba73cf6

Browse files
committed
Update spelling.go
1 parent d6d9016 commit ba73cf6

File tree

1 file changed

+36
-37
lines changed

1 file changed

+36
-37
lines changed

spelling.go

Lines changed: 36 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -26,66 +26,65 @@ func (s *Spelling) Correction(word string) string {
2626
return word
2727
}
2828

29-
if correction := s.selectBestFor(word, s.edits1(word)); correction != "" {
30-
return correction
29+
words := make(chan string)
30+
maxFreq := 0
31+
correction := ""
32+
33+
go s.genAlternativesOf(word, words, true)
34+
35+
for w := range words {
36+
if w == "" {
37+
break
38+
}
39+
40+
if freq, present := s.dic.Words[w]; present && freq > maxFreq {
41+
maxFreq, correction = freq, w
42+
}
3143
}
3244

33-
if correction := s.selectBestFor(word, s.edits2(word)); correction != "" {
45+
if correction != "" {
3446
return correction
3547
}
3648

3749
return word
3850
}
3951

40-
func (s *Spelling) edits1(word string) []string {
41-
var splits [][]string
52+
func (s *Spelling) genAlternativesOf(word string, words chan string, expand bool) {
53+
splits := [][]string{}
4254
for i := 0; i < len(word)+1; i++ {
4355
splits = append(splits, []string{word[:i], word[i:]})
4456
}
4557

46-
var words []string
47-
for _, v := range splits {
48-
l, r := v[0], v[1]
58+
callGenAltNoExpandWith := func(wordToExpand string) string {
59+
if expand {
60+
go s.genAlternativesOf(wordToExpand, words, false)
61+
}
62+
63+
return wordToExpand
64+
}
65+
66+
for _, wordPair := range splits {
67+
l, r := wordPair[0], wordPair[1]
4968
lr := len(r)
69+
5070
if lr > 0 {
51-
// Deletes
52-
words = append(words, l+r[1:])
71+
words <- callGenAltNoExpandWith(l + r[1:])
5372
}
73+
5474
if lr > 1 {
55-
// Transposes
56-
words = append(words, l+string(r[1])+string(r[0])+r[2:])
75+
words <- callGenAltNoExpandWith(l + string(r[1]) + string(r[0]) + r[2:])
5776
}
77+
5878
for _, c := range s.dic.Alphabet {
5979
if lr > 0 {
60-
// Replaces
61-
words = append(words, l+string(c)+r[1:])
80+
words <- callGenAltNoExpandWith(l + string(c) + r[1:])
6281
}
6382

64-
// Inserts
65-
words = append(words, l+string(c)+r)
83+
words <- callGenAltNoExpandWith(l + string(c) + r)
6684
}
6785
}
6886

69-
return words
70-
}
71-
72-
func (s *Spelling) edits2(word string) []string {
73-
var e2 []string
74-
for _, e1 := range s.edits1(word) {
75-
e2 = append(e2, s.edits1(e1)...)
76-
}
77-
78-
return e2
79-
}
80-
81-
func (s *Spelling) selectBestFor(word string, words []string) string {
82-
maxFreq := 0
83-
correction := ""
84-
for _, word := range words {
85-
if freq, present := s.dic.Words[word]; present && freq > maxFreq {
86-
maxFreq, correction = freq, word
87-
}
87+
if expand {
88+
words <- ""
8889
}
89-
90-
return correction
9190
}

0 commit comments

Comments
 (0)