add func for searching string slice
This commit is contained in:
parent
a3d8bf27e1
commit
90188bb18d
|
@ -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
|
||||||
|
}
|
|
@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue