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

     1  package mapexamples
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  
     8  	"github.com/m4gshm/gollections/convert/ptr"
     9  	"github.com/m4gshm/gollections/map_"
    10  	"github.com/m4gshm/gollections/map_/clone"
    11  	"github.com/m4gshm/gollections/map_/group"
    12  	"github.com/m4gshm/gollections/slice"
    13  	"github.com/m4gshm/gollections/slice/clone/sort"
    14  )
    15  
    16  type entity struct{ val string }
    17  
    18  var (
    19  	first  = entity{"1_first"}
    20  	second = entity{"2_second"}
    21  	third  = entity{"3_third"}
    22  
    23  	entities = map[int]*entity{1: &first, 2: &second, 3: &third}
    24  )
    25  
    26  func Test_DeepClone(t *testing.T) {
    27  	c := clone.Deep(entities, func(e *entity) *entity { return ptr.Of(*e) })
    28  
    29  	assert.Equal(t, entities, c)
    30  	assert.NotSame(t, entities, c)
    31  
    32  	for i := range entities {
    33  		assert.Equal(t, entities[i], c[i])
    34  		assert.NotSame(t, entities[i], c[i])
    35  	}
    36  }
    37  
    38  func Test_ValuesConverted(t *testing.T) {
    39  	var values []string = map_.ValuesConverted(entities, func(e *entity) string { return e.val })
    40  	assert.Equal(t, slice.Of("1_first", "2_second", "3_third"), sort.Asc(values))
    41  }
    42  
    43  type rows[T any] struct {
    44  	in     []T
    45  	cursor int
    46  }
    47  
    48  func (r *rows[T]) hasNext() bool    { return r.cursor < len(r.in) }
    49  func (r *rows[T]) next() (T, error) { e := r.in[r.cursor]; r.cursor++; return e, nil }
    50  
    51  func Test_OfLoop(t *testing.T) {
    52  	stream := &rows[int]{slice.Of(1, 2, 3), 0}
    53  	result, _ := map_.OfLoop(
    54  		stream,
    55  		(*rows[int]).hasNext,
    56  		func(r *rows[int]) (bool, int, error) {
    57  			n, err := r.next()
    58  			return n%2 == 0, n, err
    59  		},
    60  	)
    61  
    62  	assert.Equal(t, 2, result[true])
    63  	assert.Equal(t, 1, result[false])
    64  }
    65  
    66  func Test_Generate(t *testing.T) {
    67  	counter := 0
    68  	result, _ := map_.Generate(func() (bool, int, bool, error) {
    69  		counter++
    70  		return counter%2 == 0, counter, counter < 4, nil
    71  	})
    72  
    73  	assert.Equal(t, 2, result[true])
    74  	assert.Equal(t, 1, result[false])
    75  }
    76  
    77  func Test_GroupOfLoop(t *testing.T) {
    78  	stream := &rows[int]{slice.Of(1, 2, 3), 0}
    79  	result, _ := group.OfLoop(
    80  		stream,
    81  		(*rows[int]).hasNext,
    82  		func(r *rows[int]) (bool, int, error) {
    83  			n, err := r.next()
    84  			return n%2 == 0, n, err
    85  		},
    86  	)
    87  
    88  	assert.Equal(t, slice.Of(2), result[true])
    89  	assert.Equal(t, slice.Of(1, 3), result[false])
    90  }