-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🧹 Add basic string slice intersection fn (#1137)
- Loading branch information
1 parent
4af00d7
commit c613c65
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |