From 13beaf48a948e077b5cb510c8656bea6bdcecc18 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Sun, 27 Mar 2022 00:32:25 -0400 Subject: [PATCH] add intersection --- docs/content/collections/intersection.md | 24 ++++++++++++++++++++++++ intersection.go | 12 ++++++++++++ intersection_test.go | 17 +++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 docs/content/collections/intersection.md create mode 100644 intersection.go create mode 100644 intersection_test.go diff --git a/docs/content/collections/intersection.md b/docs/content/collections/intersection.md new file mode 100644 index 0000000..b7b4fdd --- /dev/null +++ b/docs/content/collections/intersection.md @@ -0,0 +1,24 @@ +--- +title: "Intersection" +date: 2022-03-27T00:24:11-04:00 +--- + +Intersection computes the list of values that are the intersection of all the slices. +Each value in the result is present in each of the slices. + +```go +package main + + +import ( + "fmt" + u "github.com/rjNemo/underscore" +) + +func main(){ + a := []int{1, 3, 5, 7, 9} + b := []int{2, 3, 5, 8, 0} + + fmt.Println(u.Intersection(a, b)) // {3, 5} +} +``` \ No newline at end of file diff --git a/intersection.go b/intersection.go new file mode 100644 index 0000000..40e571a --- /dev/null +++ b/intersection.go @@ -0,0 +1,12 @@ +package underscore + +// Intersection computes the list of values that are the intersection of all the slices. +// Each value in the result is present in each of the slices. +func Intersection[T comparable](a, b []T) (res []T) { + for _, n := range a { + if Contains(b, n) { + res = append(res, n) + } + } + return res +} diff --git a/intersection_test.go b/intersection_test.go new file mode 100644 index 0000000..c9f353b --- /dev/null +++ b/intersection_test.go @@ -0,0 +1,17 @@ +package underscore_test + +import ( + "testing" + + u "github.com/rjNemo/underscore" + + "github.com/stretchr/testify/assert" +) + +func TestIntersection(t *testing.T) { + a := []int{1, 3, 5, 7, 9} + b := []int{2, 3, 5, 8, 0} + want := []int{3, 5} + + assert.Equal(t, want, u.Intersection(a, b)) +}