add func for searching string slice

This commit is contained in:
Paul Meyer 2020-03-25 21:38:05 +00:00
parent a3d8bf27e1
commit 90188bb18d
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,13 @@
package common
import "strings"
// StringsContains returns true if the `haystack` contains the `needle`. Search is case insensitive.
func StringsContains(haystack []string, needle string) bool {
for _, s := range haystack {
if strings.EqualFold(s, needle) {
return true
}
}
return false
}

View File

@ -0,0 +1,39 @@
package common
import "testing"
func TestStringsContains(t *testing.T) {
tests := []struct {
name string
haystack []string
needle string
want bool
}{
{
name: "found",
haystack: []string{"a", "b", "c"},
needle: "b",
want: true,
},
{
name: "missing",
haystack: []string{"a", "b", "c"},
needle: "D",
want: false,
},
{
name: "case insensitive",
haystack: []string{"a", "b", "c"},
needle: "B",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StringsContains(tt.haystack, tt.needle); got != tt.want {
t.Errorf("StringsContains() = %v, want %v", got, tt.want)
}
})
}
}