From c613c657dab7472fdfc6ddd789ea4695d5371198 Mon Sep 17 00:00:00 2001 From: Preslav Gerchev Date: Fri, 7 Apr 2023 00:25:41 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20Add=20basic=20string=20slice=20i?= =?UTF-8?q?ntersection=20fn=20(#1137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stringx/intersection.go | 17 +++++++++++++++++ stringx/intersection_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 stringx/intersection.go create mode 100644 stringx/intersection_test.go 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) +}