Skip to content

Commit 4e06ea1

Browse files
authored
Subset function to check if one collection is a subset of another (#89)
* Create subset.go * Update subset.go * Update subset.go * Update subset.go * Create subset_test.go * Update subset.go * Update subset_test.go * Update subset_test.go
1 parent 149bba8 commit 4e06ea1

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

subset.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package funk
2+
3+
import (
4+
"reflect"
5+
)
6+
7+
// Subset returns true if collection x is a subset of y.
8+
func Subset(x interface{}, y interface{}) bool {
9+
if !IsCollection(x) {
10+
panic("First parameter must be a collection")
11+
}
12+
if !IsCollection(y) {
13+
panic("Second parameter must be a collection")
14+
}
15+
16+
xValue := reflect.ValueOf(x)
17+
xType := xValue.Type()
18+
19+
yValue := reflect.ValueOf(y)
20+
yType := yValue.Type()
21+
22+
if NotEqual(xType, yType) {
23+
panic("Parameters must have the same type")
24+
}
25+
26+
if xValue.Len() == 0 {
27+
return true
28+
}
29+
30+
if yValue.Len() == 0 || yValue.Len() < xValue.Len() {
31+
return false
32+
}
33+
34+
for i := 0; i < xValue.Len(); i++ {
35+
if !Contains(yValue.Interface(), xValue.Index(i).Interface()) {
36+
return false
37+
}
38+
return true
39+
}
40+
41+
return false
42+
43+
}

subset_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package funk
2+
3+
import (
4+
"testing"
5+
"github.com/stretchr/testify/assert"
6+
)
7+
8+
func TestSubset(t *testing.T) {
9+
is := assert.New(t)
10+
11+
r := Subset([]int{1, 2, 4}, []int{1, 2, 3, 4, 5})
12+
is.True(r)
13+
14+
r = Subset([]string{"foo", "bar"},[]string{"foo", "bar", "hello", "bar", "hi"})
15+
is.True(r)
16+
17+
r = Subset([]string{"hello", "foo", "bar", "hello", "bar", "hi"}, []string{})
18+
is.False(r)
19+
20+
r = Subset([]string{}, []string{"hello", "foo", "bar", "hello", "bar", "hi"})
21+
is.True(r)
22+
23+
r = Subset([]string{}, []string{})
24+
is.True(r)
25+
26+
r = Subset([]string{}, []string{"hello"})
27+
is.True(r)
28+
29+
r = Subset([]string{"hello", "foo", "bar", "hello", "bar", "hi"}, []string{"foo", "bar"} )
30+
is.False(r)
31+
}

0 commit comments

Comments
 (0)