mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
add groupBy function (#28)
This commit is contained in:
parent
7fef1562f2
commit
e5b3ad8ef1
2 changed files with 37 additions and 0 deletions
15
groupby.go
Normal file
15
groupby.go
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
package underscore
|
||||
|
||||
// GroupBy splits a slice into a map[K][]V grouped by the result of the iterator function.
|
||||
func GroupBy[K comparable, V any](values []V, f func(V) K) map[K][]V {
|
||||
res := make(map[K][]V, 0)
|
||||
for _, v := range values {
|
||||
k := f(v)
|
||||
if r, ok := res[k]; ok {
|
||||
res[k] = append(r, v)
|
||||
} else {
|
||||
res[k] = []V{v}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
22
groupby_test.go
Normal file
22
groupby_test.go
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package underscore_test
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
u "github.com/rjNemo/underscore"
|
||||
)
|
||||
|
||||
func TestGroupBy(t *testing.T) {
|
||||
nums := []float64{1.3, 2.1, 2.4}
|
||||
want := map[int][]float64{
|
||||
1: {1.3},
|
||||
2: {2.1, 2.4},
|
||||
}
|
||||
f := func(n float64) int {
|
||||
return int(math.Floor(n))
|
||||
}
|
||||
assert.Equal(t, want, u.GroupBy(nums, f))
|
||||
}
|
||||
Loading…
Reference in a new issue