github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/internal/examples/sliceexamples/group_Of_test.go (about)

     1  package sliceexamples
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  
     8  	"github.com/m4gshm/gollections/convert/as"
     9  	"github.com/m4gshm/gollections/expr/use"
    10  	"github.com/m4gshm/gollections/slice"
    11  	"github.com/m4gshm/gollections/slice/group"
    12  	"github.com/m4gshm/gollections/slice/sort"
    13  )
    14  
    15  func Test_Slice_Group(t *testing.T) {
    16  
    17  	var ageGroups = group.Of(users, func(u User) string {
    18  		return use.If(u.age <= 20, "<=20").If(u.age <= 30, "<=30").Else(">30")
    19  	}, as.Is)
    20  
    21  	//map[<=20:[{Tom 18 []}] <=30:[{Bob 26 []}] >30:[{Alice 35 []} {Chris 41 []}]]
    22  
    23  	assert.Equal(t, slice.Of("Alice", "Chris"), sort.Asc(slice.Convert(ageGroups[">30"], User.Name)))
    24  	assert.Equal(t, slice.Of("Bob"), slice.Convert(ageGroups["<=30"], User.Name))
    25  	assert.Equal(t, slice.Of("Tom"), slice.Convert(ageGroups["<=20"], User.Name))
    26  }