github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/loop/test/api_group_test.go (about)

     1  package test
     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/loop"
    10  	"github.com/m4gshm/gollections/loop/group"
    11  	"github.com/m4gshm/gollections/op"
    12  	"github.com/m4gshm/gollections/slice"
    13  )
    14  
    15  func Test_group_odd_even(t *testing.T) {
    16  	var (
    17  		even   = func(v int) bool { return v%2 == 0 }
    18  		groups = group.Of(loop.Of(1, 1, 2, 4, 3, 1), even, as.Is[int])
    19  	)
    20  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {2, 4}}, groups)
    21  }
    22  
    23  func Test_ByMultiple(t *testing.T) {
    24  	var (
    25  		even   = func(v int) bool { return v%2 == 0 }
    26  		groups = group.ByMultiple(loop.Of(1, 1, 2, 4, 3, 1), func(i int) []bool { return slice.Of(even(i)) }, as.Slice[int])
    27  	)
    28  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {2, 4}}, groups)
    29  }
    30  
    31  func Test_ByMultipleEmptyKey(t *testing.T) {
    32  	var (
    33  		even   = func(v int) bool { return v%2 == 0 }
    34  		groups = group.ByMultiple(loop.Of(1, 1, 2, 4, 3, 1), func(i int) []bool { return op.IfElse(even(i), slice.Of(true), nil) }, as.Slice[int])
    35  	)
    36  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {2, 4}}, groups)
    37  }
    38  
    39  func Test_ByMultipleEmptyVal(t *testing.T) {
    40  	var (
    41  		even   = func(v int) bool { return v%2 == 0 }
    42  		groups = group.ByMultiple(loop.Of(1, 1, 2, 4, 3, 1),
    43  			func(i int) []bool { return slice.Of(even(i)) },
    44  			func(i int) []int { return op.IfElse(even(i), nil, slice.Of(i)) },
    45  		)
    46  	)
    47  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {0, 0}}, groups)
    48  }
    49  
    50  func Test_ByMultipleKeys(t *testing.T) {
    51  	var (
    52  		even   = func(v int) bool { return v%2 == 0 }
    53  		groups = group.ByMultipleKeys(loop.Of(1, 1, 2, 4, 3, 1), func(i int) []bool { return slice.Of(even(i)) }, as.Is[int])
    54  	)
    55  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {2, 4}}, groups)
    56  }
    57  
    58  func Test_ByMultipleValues(t *testing.T) {
    59  
    60  	var (
    61  		even   = func(v int) bool { return v%2 == 0 }
    62  		groups = group.ByMultipleValues(loop.Of(1, 1, 2, 4, 3, 1), even, as.Slice[int])
    63  	)
    64  	assert.Equal(t, map[bool][]int{false: {1, 1, 3, 1}, true: {2, 4}}, groups)
    65  }