Skip to content

Commit 50d8885

Browse files
authored
Merge pull request #11 from beonode/set-intersection
Add SetIntersect() method
2 parents 835a2e9 + a4b2e3b commit 50d8885

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

sets.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,22 @@ func SetMerge(a []string, b []string) []string {
6666
return merged
6767
}
6868

69+
// SetIntersect will return all elements present in both a and b
70+
func SetIntersect(a []string, b []string) []string {
71+
intersection := make([]string, 0)
72+
73+
for _, aVal := range a {
74+
for _, bVal := range b {
75+
if aVal == bVal {
76+
intersection = append(intersection, aVal)
77+
break
78+
}
79+
}
80+
}
81+
82+
return intersection
83+
}
84+
6985
// SortByKeys returns a new ordered slice based on the keys ordering
7086
func SortByKeys(keys []string, strs []string) []string {
7187
resultLen := len(strs)

sets_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,39 @@ func TestSetMerge(t *testing.T) {
9898
}
9999
}
100100

101+
func TestSetIntersect(t *testing.T) {
102+
t.Parallel()
103+
104+
tests := []struct {
105+
A []string
106+
B []string
107+
C []string
108+
}{
109+
{
110+
[]string{"a", "b", "c"},
111+
[]string{"a", "b", "c"},
112+
[]string{"a", "b", "c"},
113+
},
114+
{
115+
[]string{"a", "b", "c"},
116+
[]string{"b", "c", "d"},
117+
[]string{"b", "c"},
118+
},
119+
{
120+
[]string{"a", "b", "c"},
121+
[]string{"d", "e", "f"},
122+
[]string{},
123+
},
124+
}
125+
126+
for i, test := range tests {
127+
intersection := SetIntersect(test.A, test.B)
128+
if !reflect.DeepEqual(test.C, intersection) {
129+
t.Errorf("[%d] mismatch:\nWant: %#v\nGot: %#v", i, test.C, intersection)
130+
}
131+
}
132+
}
133+
101134
func TestSortByKeys(t *testing.T) {
102135
t.Parallel()
103136

0 commit comments

Comments
 (0)