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

feat: add Partition for slice

This commit is contained in:
dudaodong
2023-09-04 11:30:50 +08:00
parent 4037b96cc4
commit 541e6d4ea3
3 changed files with 59 additions and 2 deletions

View File

@@ -1192,10 +1192,40 @@ func KeyBy[T any, U comparable](slice []T, iteratee func(item T) U) map[U]T {
// Join the slice item with specify separator.
// Play: https://go.dev/play/p/huKzqwNDD7V
func Join[T any](s []T, separator string) string {
str := Map(s, func(_ int, item T) string {
func Join[T any](slice []T, separator string) string {
str := Map(slice, func(_ int, item T) string {
return fmt.Sprint(item)
})
return strings.Join(str, separator)
}
// Partition all slice elements with the evaluation of the given predicate functions.
// todo
func Partition[T any](slice []T, predicates ...func(item T) bool) [][]T {
l := len(predicates)
result := make([][]T, l+1)
for _, item := range slice {
processed := false
for i, f := range predicates {
if f == nil {
panic("predicate function must not be nill")
}
if f(item) {
result[i] = append(result[i], item)
processed = true
break
}
}
if !processed {
result[l] = append(result[l], item)
}
}
return result
}