From 1d87b4a5949deebeb6ed90fc1f278b8a17ff1ba3 Mon Sep 17 00:00:00 2001 From: pospispa Date: Thu, 23 Nov 2017 16:00:35 +0100 Subject: [PATCH] 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. --- slice.go | 21 +++++++++++++++++ slice_test.go | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/slice.go b/slice.go index b408dbae..b9809cc2 100644 --- a/slice.go +++ b/slice.go @@ -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 +} diff --git a/slice_test.go b/slice_test.go index c39f54c1..19b46c22 100644 --- a/slice_test.go +++ b/slice_test.go @@ -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) + } + } +}