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

feat: add ContainBy function

This commit is contained in:
dudaodong
2023-02-24 14:19:10 +08:00
parent e523d4af6e
commit 9d2c9806d1
5 changed files with 152 additions and 1 deletions

View File

@@ -24,6 +24,7 @@ import (
- [AppendIfAbsent](#AppendIfAbsent)
- [Contain](#Contain)
- [ContainBy](#ContainBy)
- [ContainSubSlice](#ContainSubSlice)
- [Chunk](#Chunk)
- [Compact](#Compact)
@@ -151,6 +152,51 @@ func main() {
}
```
### <span id="ContainBy">ContainBy</span>
<p>returns true if predicate function return true.</p>
<b>Signature:</b>
```go
func ContainBy[T any](slice []T, predicate func(item T) bool) bool
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
type foo struct {
A string
B int
}
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// false
// true
// false
}
```
### <span id="ContainSubSlice">ContainSubSlice</span>
<p>Check if the slice contain subslice or not.</p>

View File

@@ -24,6 +24,7 @@ import (
- [AppendIfAbsent](#AppendIfAbsent)
- [Contain](#Contain)
- [ContainBy](#ContainBy)
- [ContainSubSlice](#ContainSubSlice)
- [Chunk](#Chunk)
- [Compact](#Compact)
@@ -151,6 +152,51 @@ func main() {
}
```
### <span id="ContainBy">ContainBy</span>
<p>根据predicate函数判断切片是否包含某个值。</p>
<b>函数签名:</b>
```go
func ContainBy[T any](slice []T, predicate func(item T) bool) bool
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
type foo struct {
A string
B int
}
array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := slice.ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := slice.ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })
array2 := []string{"a", "b", "c"}
result3 := slice.ContainBy(array2, func(t string) bool { return t == "a" })
result4 := slice.ContainBy(array2, func(t string) bool { return t == "d" })
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// false
// true
// false
}
```
### <span id="ContainSubSlice">ContainSubSlice</span>
<p>判断slice是否包含subslice</p>