Skip to content

Commit

Permalink
Subset function to check if one collection is a subset of another (#89)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
reetuparna authored Jun 21, 2020
1 parent 149bba8 commit 4e06ea1
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
43 changes: 43 additions & 0 deletions subset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package funk

import (
"reflect"
)

// Subset returns true if collection x is a subset of y.
func Subset(x interface{}, y interface{}) bool {
if !IsCollection(x) {
panic("First parameter must be a collection")
}
if !IsCollection(y) {
panic("Second parameter must be a collection")
}

xValue := reflect.ValueOf(x)
xType := xValue.Type()

yValue := reflect.ValueOf(y)
yType := yValue.Type()

if NotEqual(xType, yType) {
panic("Parameters must have the same type")
}

if xValue.Len() == 0 {
return true
}

if yValue.Len() == 0 || yValue.Len() < xValue.Len() {
return false
}

for i := 0; i < xValue.Len(); i++ {
if !Contains(yValue.Interface(), xValue.Index(i).Interface()) {
return false
}
return true
}

return false

}
31 changes: 31 additions & 0 deletions subset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package funk

import (
"testing"
"github.com/stretchr/testify/assert"
)

func TestSubset(t *testing.T) {
is := assert.New(t)

r := Subset([]int{1, 2, 4}, []int{1, 2, 3, 4, 5})
is.True(r)

r = Subset([]string{"foo", "bar"},[]string{"foo", "bar", "hello", "bar", "hi"})
is.True(r)

r = Subset([]string{"hello", "foo", "bar", "hello", "bar", "hi"}, []string{})
is.False(r)

r = Subset([]string{}, []string{"hello", "foo", "bar", "hello", "bar", "hi"})
is.True(r)

r = Subset([]string{}, []string{})
is.True(r)

r = Subset([]string{}, []string{"hello"})
is.True(r)

r = Subset([]string{"hello", "foo", "bar", "hello", "bar", "hi"}, []string{"foo", "bar"} )
is.False(r)
}

0 comments on commit 4e06ea1

Please sign in to comment.