...
1 package validator
2
3 import (
4 "sort"
5 "strings"
6
7 "github.com/agnivade/levenshtein"
8 )
9
10
11
12 func SuggestionList(input string, options []string) []string {
13 var results []string
14 optionsByDistance := map[string]int{}
15
16 for _, option := range options {
17 distance := lexicalDistance(input, option)
18 threshold := calcThreshold(input, option)
19 if distance <= threshold {
20 results = append(results, option)
21 optionsByDistance[option] = distance
22 }
23 }
24
25 sort.Slice(results, func(i, j int) bool {
26 return optionsByDistance[results[i]] < optionsByDistance[results[j]]
27 })
28 return results
29 }
30
31 func calcThreshold(a, b string) (threshold int) {
32 if len(a) >= len(b) {
33 threshold = len(a) / 2
34 } else {
35 threshold = len(b) / 2
36 }
37 if threshold < 1 {
38 threshold = 1
39 }
40 return
41 }
42
43
44
45
46
47
48
49
50
51
52
53
54
55 func lexicalDistance(a, b string) int {
56 if a == b {
57 return 0
58 }
59
60 a = strings.ToLower(a)
61 b = strings.ToLower(b)
62
63
64 if a == b {
65 return 1
66 }
67
68 return levenshtein.ComputeDistance(a, b)
69 }
70
View as plain text