add intersection

This commit is contained in:
Ruidy 2022-03-27 00:32:25 -04:00
parent 6a1a4c157b
commit 13beaf48a9
3 changed files with 53 additions and 0 deletions

View file

@ -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}
}
```

12
intersection.go Normal file
View file

@ -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
}

17
intersection_test.go Normal file
View file

@ -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))
}