Skip to content

Commit

Permalink
Add InFoldedStringSlice & StringMap
Browse files Browse the repository at this point in the history
  • Loading branch information
cesartw committed Nov 12, 2021
1 parent 61c8125 commit 102230e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
22 changes: 21 additions & 1 deletion sliceutil/sliceutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
25 changes: 25 additions & 0 deletions sliceutil/sliceutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 102230e

Please sign in to comment.