diff options
author | Jesse Duffield <jessedduffield@gmail.com> | 2020-11-28 13:14:48 +1100 |
---|---|---|
committer | Jesse Duffield <jessedduffield@gmail.com> | 2020-11-28 20:48:17 +1100 |
commit | da3b0bf7c8aa6202d5eb9c8178f6648bc695336a (patch) | |
tree | cd0666ae4253469f8f2f1e349357be37bfb3d571 /pkg/utils | |
parent | 90ade3225f55652d40c6f0266e50f5328390f02b (diff) |
Start on supporting auto-suggestions when checking out a branch
switch to other fuzzy package with no dependencies
Diffstat (limited to 'pkg/utils')
-rw-r--r-- | pkg/utils/fuzzy_search.go | 28 | ||||
-rw-r--r-- | pkg/utils/fuzzy_search_test.go | 53 |
2 files changed, 81 insertions, 0 deletions
diff --git a/pkg/utils/fuzzy_search.go b/pkg/utils/fuzzy_search.go new file mode 100644 index 000000000..c4bc078a3 --- /dev/null +++ b/pkg/utils/fuzzy_search.go @@ -0,0 +1,28 @@ +package utils + +import ( + "sort" + + "github.com/sahilm/fuzzy" +) + +func FuzzySearch(needle string, haystack []string) []string { + if needle == "" { + return []string{} + } + + myHaystack := make([]string, len(haystack)) + for i := range haystack { + myHaystack[i] = haystack[i] + } + + matches := fuzzy.Find(needle, haystack) + sort.Sort(matches) + + result := make([]string, len(matches)) + for i, match := range matches { + result[i] = match.Str + } + + return result +} diff --git a/pkg/utils/fuzzy_search_test.go b/pkg/utils/fuzzy_search_test.go new file mode 100644 index 000000000..808d83772 --- /dev/null +++ b/pkg/utils/fuzzy_search_test.go @@ -0,0 +1,53 @@ +package utils + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestFuzzySearch is a function. +func TestFuzzySearch(t *testing.T) { + type scenario struct { + needle string + haystack []string + expected []string + } + + scenarios := []scenario{ + { + needle: "", + haystack: []string{"test"}, + expected: []string{}, + }, + { + needle: "test", + haystack: []string{"test"}, + expected: []string{"test"}, + }, + { + needle: "o", + haystack: []string{"a", "o", "e"}, + expected: []string{"o"}, + }, + { + needle: "mybranch", + haystack: []string{"my_branch", "mybranch", "branch", "this is my branch"}, + expected: []string{"mybranch", "my_branch", "this is my branch"}, + }, + { + needle: "test", + haystack: []string{"not a good match", "this 'test' is a good match", "test"}, + expected: []string{"test", "this 'test' is a good match"}, + }, + { + needle: "test", + haystack: []string{"Test"}, + expected: []string{"Test"}, + }, + } + + for _, s := range scenarios { + assert.EqualValues(t, s.expected, FuzzySearch(s.needle, s.haystack)) + } +} |