mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
parent
6a1a4c157b
commit
1166c701ac
3 changed files with 53 additions and 0 deletions
24
docs/content/collections/intersection.md
Normal file
24
docs/content/collections/intersection.md
Normal 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
12
intersection.go
Normal 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
17
intersection_test.go
Normal 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))
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue