From 4e06ea1449c7da9cb79ff16084b086d5b873637c Mon Sep 17 00:00:00 2001 From: Reetuparna Mukherjee Date: Sun, 21 Jun 2020 15:21:46 +0530 Subject: [PATCH] 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 --- subset.go | 43 +++++++++++++++++++++++++++++++++++++++++++ subset_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 subset.go create mode 100644 subset_test.go diff --git a/subset.go b/subset.go new file mode 100644 index 0000000..1f814b7 --- /dev/null +++ b/subset.go @@ -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 + +} diff --git a/subset_test.go b/subset_test.go new file mode 100644 index 0000000..f489d18 --- /dev/null +++ b/subset_test.go @@ -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) +}