diff --git a/sliceutil/sliceutil.go b/sliceutil/sliceutil.go index e1a19e6..3d44279 100644 --- a/sliceutil/sliceutil.go +++ b/sliceutil/sliceutil.go @@ -91,7 +91,7 @@ func CSVtoInt64Slice(csv string) ([]int64, error) { return ints, nil } -// InStringSlice reports whether str is within list +// InStringSlice reports whether str is within list(case-sensitive) func InStringSlice(list []string, str string) bool { for _, item := range list { if item == str { @@ -101,6 +101,16 @@ func InStringSlice(list []string, str string) bool { return false } +// InFoldedStringSlice reports whether str is within list(case-insensitive) +func InFoldedStringSlice(list []string, str string) bool { + for _, item := range list { + if strings.EqualFold(item, str) { + return true + } + } + return false +} + // InIntSlice reports whether i is within list func InIntSlice(list []int, i int) bool { for _, item := range list { @@ -194,3 +204,13 @@ func FilterInt(list []int64, fun func(int64) bool) []int64 { func FilterIntEmpty(e int64) bool { return e != 0 } + +// StringMap returns a list strings where each item in list has been modified by f +func StringMap(list []string, f func(string) string) []string { + ret := make([]string, len(list)) + for i := range list { + ret[i] = f(list[i]) + } + + return ret +} diff --git a/sliceutil/sliceutil_test.go b/sliceutil/sliceutil_test.go index 1ae5b33..864f0a2 100644 --- a/sliceutil/sliceutil_test.go +++ b/sliceutil/sliceutil_test.go @@ -260,6 +260,31 @@ func TestInStringSlice(t *testing.T) { } } +func TestInFoldedStringSlice(t *testing.T) { + tests := []struct { + list []string + find string + expected bool + }{ + {[]string{"hello"}, "hello", true}, + {[]string{"HELLO"}, "hello", true}, + {[]string{"hello"}, "HELLO", true}, + {[]string{"hello"}, "hell", false}, + {[]string{"hello", "world", "test"}, "world", true}, + {[]string{"hello", "world", "test"}, "", false}, + {[]string{}, "", false}, + } + + for i, tc := range tests { + t.Run(fmt.Sprintf("test-%v", i), func(t *testing.T) { + got := InFoldedStringSlice(tc.list, tc.find) + if got != tc.expected { + t.Errorf(diff.Cmp(tc.expected, got)) + } + }) + } +} + func TestInIntSlice(t *testing.T) { tests := []struct { list []int