Skip to content

Commit

Permalink
add sfx and prefix slice matches
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed May 19, 2023
1 parent 81867a7 commit 5d4dded
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 2 deletions.
20 changes: 20 additions & 0 deletions stringutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,23 @@ func HasCommonElement(a, b []string) bool {
}
return false
}

// HasPrefixSlice checks if any string in the slice starts with the given prefix
func HasPrefixSlice(prefix string, slice []string) bool {
for _, v := range slice {
if strings.HasPrefix(v, prefix) {
return true
}
}
return false
}

// HasSuffixSlice checks if any string in the slice ends with the given suffix
func HasSuffixSlice(suffix string, slice []string) bool {
for _, v := range slice {
if strings.HasSuffix(v, suffix) {
return true
}
}
return false
}
60 changes: 58 additions & 2 deletions stringutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func TestSliceToString(t *testing.T) {
}

func TestHasCommonElement(t *testing.T) {
cases := []struct {
tests := []struct {
name string
a, b []string
want bool
Expand All @@ -107,9 +107,65 @@ func TestHasCommonElement(t *testing.T) {
{"element found at the end", []string{"a", "b", "c", "d"}, []string{"x", "y", "z", "d"}, true},
}

for _, tc := range cases {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, HasCommonElement(tc.a, tc.b))
})
}
}

func TestHasPrefixSlice(t *testing.T) {
tests := []struct {
name string
slice []string
prefix string
exp bool
}{
{
name: "prefix exists",
slice: []string{"apple", "banana", "cherry"},
prefix: "ap",
exp: true,
},
{
name: "prefix does not exist",
slice: []string{"apple", "banana", "cherry"},
prefix: "kiwi",
exp: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.exp, HasPrefixSlice(tt.prefix, tt.slice))
})
}
}

func TestHasSuffixSlice(t *testing.T) {
tests := []struct {
name string
slice []string
suffix string
exp bool
}{
{
name: "suffix exists",
slice: []string{"apple", "banana", "cherry"},
suffix: "na",
exp: true,
},
{
name: "suffix does not exist",
slice: []string{"apple", "banana", "cherry"},
suffix: "kiwi",
exp: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.exp, HasSuffixSlice(tt.suffix, tt.slice))
})
}
}

0 comments on commit 5d4dded

Please sign in to comment.