mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-05 21:32:27 +08:00
feat: add GroupWith func
This commit is contained in:
@@ -253,6 +253,25 @@ func GroupBy[T any](slice []T, groupFn func(index int, t T) bool) ([]T, []T) {
|
||||
return groupA, groupB
|
||||
}
|
||||
|
||||
// GroupWith return a map composed of keys generated from the results of running each element of slice thru iteratee.
|
||||
func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T {
|
||||
if iteratee == nil {
|
||||
panic("iteratee func is missing")
|
||||
}
|
||||
|
||||
res := make(map[U][]T)
|
||||
|
||||
for _, v := range slice {
|
||||
key := iteratee(v)
|
||||
if _, ok := res[key]; !ok {
|
||||
res[key] = []T{}
|
||||
}
|
||||
res[key] = append(res[key], v)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// Find iterates over elements of slice, returning the first one that passes a truth test on predicate function.
|
||||
// If return T is nil then no items matched the predicate func
|
||||
func Find[T any](slice []T, predicate func(index int, t T) bool) (*T, bool) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package slice
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/duke-git/lancet/v2/internal"
|
||||
@@ -142,6 +143,20 @@ func TestGroupBy(t *testing.T) {
|
||||
assert.Equal(expectedOdd, odd)
|
||||
}
|
||||
|
||||
func TestGroupWith(t *testing.T) {
|
||||
nums := []float64{6.1, 4.2, 6.3}
|
||||
floor := func(num float64) float64 {
|
||||
return math.Floor(num)
|
||||
}
|
||||
expected := map[float64][]float64{
|
||||
4: {4.2},
|
||||
6: {6.1, 6.3},
|
||||
}
|
||||
actual := GroupWith(nums, floor)
|
||||
assert := internal.NewAssert(t, "TestGroupWith")
|
||||
assert.Equal(expected, actual)
|
||||
}
|
||||
|
||||
func TestCount(t *testing.T) {
|
||||
nums := []int{1, 2, 3, 4, 5, 6}
|
||||
evenFunc := func(i, num int) bool {
|
||||
|
||||
Reference in New Issue
Block a user