Addressing Comments from Code Review

Addressing comments from code review (https://github.com/kubernetes/kubernetes/pull/55824#pullrequestreview-78597250) in order to simplify the code.
This commit is contained in:
pospispa
2017-11-23 16:00:35 +01:00
parent 2aeace402a
commit e1312f2c00
9 changed files with 101 additions and 287 deletions

View File

@@ -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
}

View File

@@ -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)
}
}
}