11package utils
22
3+ import (
4+ "sort"
5+ "strings"
6+ "github.com/lithammer/fuzzysearch/fuzzy"
7+ )
8+
9+
310type CfJavaPluginUtil interface {
411 FindReasonForAccessError (app string ) string
512 CheckRequiredTools (app string ) (bool , error )
@@ -11,3 +18,46 @@ type CfJavaPluginUtil interface {
1118 FindFile (args []string , fullpath string , fspath string , pattern string ) (string , error )
1219 ListFiles (args []string , path string ) ([]string , error )
1320}
21+
22+ // FuzzySearch returns up to `max` words from `words` that are closest in
23+ // Levenshtein distance to `needle`.
24+ func FuzzySearch (needle string , words []string , max int ) []string {
25+ type match struct {
26+ distance int
27+ word string
28+ }
29+
30+ matches := make ([]match , 0 , len (words ))
31+ for _ , w := range words {
32+ matches = append (matches , match {
33+ distance : fuzzy .LevenshteinDistance (needle , w ),
34+ word : w ,
35+ })
36+ }
37+
38+ sort .Slice (matches , func (i , j int ) bool {
39+ return matches [i ].distance < matches [j ].distance
40+ })
41+
42+ if max > len (matches ) {
43+ max = len (matches )
44+ }
45+
46+ results := make ([]string , 0 , max )
47+ for i := 0 ; i < max ; i ++ {
48+ results = append (results , matches [i ].word )
49+ }
50+
51+ return results
52+ }
53+
54+ // "x, y, or z"
55+ func JoinWithOr (a []string ) string {
56+ if len (a ) == 0 {
57+ return ""
58+ }
59+ if len (a ) == 1 {
60+ return a [0 ]
61+ }
62+ return strings .Join (a [:len (a ) - 1 ], ", " ) + ", or " + a [len (a ) - 1 ]
63+ }
0 commit comments