github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/utils/generics_test.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "reflect" 6 "strconv" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestMap(t *testing.T) { 13 s1 := []int{1, 2, 3, 4, 5} 14 s2 := Map(s1, func(e int) string { 15 return fmt.Sprintf("%d", e) 16 }) 17 assert.Equal(t, []string{"1", "2", "3", "4", "5"}, s2) 18 } 19 20 func TestSum(t *testing.T) { 21 s1 := []int{1, 2, 3, 4, 5} 22 s2 := Sum(s1) 23 assert.Equal(t, 15, s2) 24 } 25 26 func TestMin(t *testing.T) { 27 assert.Equal(t, 1, Min(1, 2, 3)) 28 assert.Equal(t, 1.0, Min(2.0, 1.0, 3.0)) 29 assert.Equal(t, uint32(1), Min(uint32(2), uint32(1), uint32(3))) 30 } 31 32 func TestMax(t *testing.T) { 33 assert.Equal(t, 3, Max(1, 2, 3)) 34 assert.Equal(t, 3.0, Max(2.0, 1.0, 3.0)) 35 assert.Equal(t, uint32(3), Max(uint32(2), uint32(1), uint32(3))) 36 } 37 38 func TestAny(t *testing.T) { 39 s1 := []int{1, 2, 3, 4, 5} 40 s2 := Any(s1, func(e int) bool { 41 return e == 3 42 }) 43 assert.True(t, s2) 44 s1 = nil 45 s2 = Any(s1, func(e int) bool { 46 return e == 3 47 }) 48 assert.False(t, s2) 49 } 50 51 func TestFilter(t *testing.T) { 52 var s0 []int 53 s0 = Filter(s0, func(int) bool { return true }) 54 assert.Nil(t, s0) 55 56 s1 := GenerateSlice(5, func() int { 57 return 0 58 }) 59 s2 := Filter(s1, func(int) bool { return true }) 60 assert.Len(t, s2, 5) 61 } 62 63 func TestGenerateSlice(t *testing.T) { 64 s1 := GenerateSlice(5, func() int { 65 return 0 66 }) 67 assert.Equal(t, []int{0, 0, 0, 0, 0}, s1) 68 s2 := GenerateSlice(0, func() int { 69 return 0 70 }) 71 assert.Equal(t, []int{}, s2) 72 } 73 74 func TestAdvancedDivide(t *testing.T) { 75 s1 := AdvancedDivide(0, 0) 76 assert.Equal(t, 0, s1) 77 s2 := AdvancedDivide(1, 0) 78 assert.Equal(t, 0, s2) 79 s3 := AdvancedDivide(1, 1) 80 assert.Equal(t, 1, s3) 81 } 82 83 func TestReverse(t *testing.T) { 84 s1 := []string{"a", "b", "c"} 85 Reverse(s1) 86 assert.True(t, reflect.DeepEqual(s1, []string{"c", "b", "a"})) 87 88 s2 := []string{} 89 Reverse(s2) 90 91 s3 := []int{1, 2, 3, 4} 92 Reverse(s3) 93 assert.True(t, reflect.DeepEqual(s3, []int{4, 3, 2, 1})) 94 } 95 96 func TestUnique(t *testing.T) { 97 s1 := []int64{1, 2, 3} 98 s1 = s1[:Unique(s1, func(i int) string { return strconv.Itoa(int(s1[i])) })] 99 assert.True(t, reflect.DeepEqual(s1, []int64{1, 2, 3})) 100 101 s2 := []string{"a", "a", "a", "b", "b", "c"} 102 s2 = s2[:Unique(s2, func(i int) string { return s2[i] })] 103 assert.True(t, reflect.DeepEqual(s2, []string{"a", "b", "c"})) 104 105 s3 := []string{"", "1", "1", "1", "1"} 106 s3 = s3[:Unique(s3, func(i int) string { return s3[i] })] 107 assert.True(t, reflect.DeepEqual(s3, []string{"", "1"})) 108 }