1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add ContainAny (#338)

Co-authored-by: Jiawen <im@linjiawen.com>
This commit is contained in:
Javen
2025-10-30 19:24:45 +08:00
committed by GitHub
parent fc624195c7
commit 350450bb67
7 changed files with 161 additions and 0 deletions

View File

@@ -74,6 +74,27 @@ func ContainSubSlice[T comparable](slice, subSlice []T) bool {
return true
}
// ContainAny check if the slice contains any element from the targets slice.
// Play: https://go.dev/play/p/4xoxhc9XSSw
func ContainAny[T comparable](slice []T, targets []T) bool {
if len(targets) == 0 {
return false
}
sliceMap := make(map[T]struct{}, len(slice))
for _, item := range slice {
sliceMap[item] = struct{}{}
}
for _, target := range targets {
if _, exists := sliceMap[target]; exists {
return true
}
}
return false
}
// Chunk creates a slice of elements split into groups the length of size.
// Play: https://go.dev/play/p/b4Pou5j2L_C
func Chunk[T any](slice []T, size int) [][]T {

View File

@@ -58,6 +58,24 @@ func ExampleContainSubSlice() {
// false
}
func ExampleContainAny() {
result1 := ContainAny([]string{"a", "b", "c"}, []string{"a"})
result2 := ContainAny([]string{"a", "b", "c"}, []string{"d", "e"})
result3 := ContainAny([]string{"a", "b", "c"}, []string{"d", "a"})
result4 := ContainAny([]string{"a", "b", "c"}, []string{})
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// false
// true
// false
}
func ExampleChunk() {
arr := []string{"a", "b", "c", "d", "e"}

View File

@@ -89,6 +89,46 @@ func TestContainSubSlice(t *testing.T) {
}
}
func TestContainAny(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestContainAny")
tests := []struct {
slice []string
targets []string
want bool
}{
{[]string{"a", "b", "c"}, []string{"a"}, true},
{[]string{"a", "b", "c"}, []string{"a", "b"}, true},
{[]string{"a", "b", "c"}, []string{"d", "e"}, false},
{[]string{"a", "b", "c"}, []string{"d", "a"}, true},
{[]string{"a", "b", "c"}, []string{}, false},
{[]string{}, []string{"a"}, false},
{[]string{}, []string{}, false},
{[]string{"a", "b", "c"}, []string{"c", "d", "e"}, true},
}
for _, tt := range tests {
assert.Equal(tt.want, ContainAny(tt.slice, tt.targets))
}
intTests := []struct {
slice []int
targets []int
want bool
}{
{[]int{1, 2, 3, 4, 5}, []int{3}, true},
{[]int{1, 2, 3, 4, 5}, []int{6, 7}, false},
{[]int{1, 2, 3, 4, 5}, []int{5, 6, 7}, true},
{[]int{1, 2, 3, 4, 5}, []int{}, false},
}
for _, tt := range intTests {
assert.Equal(tt.want, ContainAny(tt.slice, tt.targets))
}
}
func TestChunk(t *testing.T) {
t.Parallel()