...
1 package validator
2
3 import (
4 "math"
5 "sort"
6 "strings"
7
8 "github.com/agnivade/levenshtein"
9 )
10
11
12
13 func SuggestionList(input string, options []string) []string {
14 var results []string
15 optionsByDistance := map[string]int{}
16
17 for _, option := range options {
18 distance := lexicalDistance(input, option)
19 threshold := calcThreshold(input)
20 if distance <= threshold {
21 results = append(results, option)
22 optionsByDistance[option] = distance
23 }
24 }
25
26 sort.Slice(results, func(i, j int) bool {
27 return optionsByDistance[results[i]] < optionsByDistance[results[j]]
28 })
29 return results
30 }
31
32 func calcThreshold(a string) (threshold int) {
33
34
35 threshold = int(math.Floor(float64(len(a))*0.4) + 1)
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