Skip to content

Commit

Permalink
shared: Adds method to remove elements from a slice.
Browse files Browse the repository at this point in the history
Also adds tests for method.

Signed-off-by: Mark Laing <[email protected]>
  • Loading branch information
markylaing committed Apr 1, 2022
1 parent 4e6171e commit 28d3366
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
22 changes: 22 additions & 0 deletions shared/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,28 @@ func StringInSlice(key string, list []string) bool {
return false
}

// RemoveElementsFromStringSlice returns a slice equivalent to removing the given elements from the given list.
// Elements not present in the list are ignored.
func RemoveElementsFromStringSlice(list []string, elements ...string) []string {
for i := len(elements) - 1; i >= 0; i-- {
element := elements[i]
match := false
for j := len(list) - 1; j >= 0; j-- {
if element == list[j] {
match = true
list = append(list[:j], list[j+1:]...)
break
}
}

if match {
elements = append(elements[:i], elements[i+1:]...)
}
}

return list
}

// StringHasPrefix returns true if value has one of the supplied prefixes.
func StringHasPrefix(value string, prefixes ...string) bool {
for _, prefix := range prefixes {
Expand Down
40 changes: 40 additions & 0 deletions shared/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,43 @@ func TestHasKey(t *testing.T) {
assert.True(t, HasKey(1, m2))
assert.False(t, HasKey(0, m2))
}

func TestRemoveElementsFromStringSlice(t *testing.T) {
type test struct {
elementsToRemove []string
list []string
expectedList []string
}
tests := []test{
{
elementsToRemove: []string{"one", "two", "three"},
list: []string{"one", "two", "three", "four", "five"},
expectedList: []string{"four", "five"},
},
{
elementsToRemove: []string{"two", "three", "four"},
list: []string{"one", "two", "three", "four", "five"},
expectedList: []string{"one", "five"},
},
{
elementsToRemove: []string{"two", "three", "four"},
list: []string{"two", "three"},
expectedList: []string{},
},
{
elementsToRemove: []string{"two", "two", "two"},
list: []string{"two"},
expectedList: []string{},
},
{
elementsToRemove: []string{"two", "two", "two"},
list: []string{"one", "two", "three", "four", "five"},
expectedList: []string{"one", "three", "four", "five"},
},
}

for _, tt := range tests {
gotList := RemoveElementsFromStringSlice(tt.list, tt.elementsToRemove...)
assert.ElementsMatch(t, tt.expectedList, gotList)
}
}

0 comments on commit 28d3366

Please sign in to comment.