Skip to content

Commit

Permalink
Addressing Comments from Code Review
Browse files Browse the repository at this point in the history
Addressing comments from code review (kubernetes/kubernetes#55824 (review)) in order to simplify the code.
  • Loading branch information
pospispa committed Nov 29, 2017
1 parent 562cacc commit 1d87b4a
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
21 changes: 21 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,24 @@ func ContainsString(slice []string, s string, modifier func(s string) string) bo
}
return false
}

// RemoveString returns a newly created []string that contains all items from slice that
// are not equal to s and modifier(s) in case modifier func is provided.
func RemoveString(slice []string, s string, modifier func(s string) string) []string {
newSlice := make([]string, 0)
for _, item := range slice {
if item == s {
continue
}
if modifier != nil && modifier(item) == s {
continue
}
newSlice = append(newSlice, item)
}
if len(newSlice) == 0 {
// Sanitize for unit tests so we don't need to distinguish empty array
// and nil.
newSlice = nil
}
return newSlice
}
64 changes: 64 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,67 @@ func TestContainsString(t *testing.T) {
t.Errorf("ContainsString didn't find the string by modifier")
}
}

func TestRemoveString(t *testing.T) {
modifier := func(s string) string {
if s == "ab" {
return "ee"
}
return s
}
tests := []struct {
testName string
input []string
remove string
modifier func(s string) string
want []string
}{
{
testName: "Nil input slice",
input: nil,
remove: "",
modifier: nil,
want: nil,
},
{
testName: "Slice doesn't contain the string",
input: []string{"a", "ab", "cdef"},
remove: "NotPresentInSlice",
modifier: nil,
want: []string{"a", "ab", "cdef"},
},
{
testName: "All strings removed, result is nil",
input: []string{"a"},
remove: "a",
modifier: nil,
want: nil,
},
{
testName: "No modifier func, one string removed",
input: []string{"a", "ab", "cdef"},
remove: "ab",
modifier: nil,
want: []string{"a", "cdef"},
},
{
testName: "No modifier func, all(three) strings removed",
input: []string{"ab", "a", "ab", "cdef", "ab"},
remove: "ab",
modifier: nil,
want: []string{"a", "cdef"},
},
{
testName: "Removed both the string and the modifier func result",
input: []string{"a", "cd", "ab", "ee"},
remove: "ee",
modifier: modifier,
want: []string{"a", "cd"},
},
}
for _, tt := range tests {
if got := RemoveString(tt.input, tt.remove, tt.modifier); !reflect.DeepEqual(got, tt.want) {
t.Errorf("%v: RemoveString(%v, %q, %T) = %v WANT %v", tt.testName, tt.input, tt.remove, tt.modifier, got, tt.want)
}
}
}

0 comments on commit 1d87b4a

Please sign in to comment.