Skip to content

Commit

Permalink
🧹 Add basic string slice intersection fn (#1137)
Browse files Browse the repository at this point in the history
  • Loading branch information
preslavgerchev authored Apr 6, 2023
1 parent 4af00d7 commit c613c65
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions stringx/intersection.go
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 24 additions & 0 deletions stringx/intersection_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit c613c65

Please sign in to comment.