From 50ef63e27d5453eaf73300ca40d2fdade01400a1 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 21 Mar 2022 15:29:10 +0800 Subject: [PATCH] feat: add GroupWith func --- slice/slice.go | 19 +++++++++++++++++++ slice/slice_test.go | 15 +++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index d6919e9..bf7d7d2 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -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) { diff --git a/slice/slice_test.go b/slice/slice_test.go index fb95288..7951b7b 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -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 {