diff --git a/stringx/intersection.go b/stringx/intersection.go new file mode 100644 index 0000000000..ff5281b01f --- /dev/null +++ b/stringx/intersection.go @@ -0,0 +1,17 @@ +package stringx + +func Intersection(a, b []string) []string { + entriesMap := map[string]struct{}{} + res := []string{} + + for i := range a { + entriesMap[a[i]] = struct{}{} + } + + for i := range b { + if _, ok := entriesMap[b[i]]; ok { + res = append(res, b[i]) + } + } + return res +} diff --git a/stringx/intersection_test.go b/stringx/intersection_test.go new file mode 100644 index 0000000000..5930ed1fc1 --- /dev/null +++ b/stringx/intersection_test.go @@ -0,0 +1,24 @@ +package stringx + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIntersection(t *testing.T) { + a := []string{"a", "b", "c"} + b := []string{"b", "c", "d", "f"} + + actual := Intersection(a, b) + expected := []string{"b", "c"} + assert.ElementsMatch(t, actual, expected) +} + +func TestIntersectionNoOverlap(t *testing.T) { + a := []string{"a", "b", "c"} + b := []string{"d", "f"} + + actual := Intersection(a, b) + assert.Empty(t, actual) +}