github.com/go-playground/pkg/v5@v5.29.1/slice/slice_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package sliceext 5 6 import ( 7 . "github.com/go-playground/assert/v2" 8 optionext "github.com/go-playground/pkg/v5/values/option" 9 "strconv" 10 "testing" 11 ) 12 13 func TestFilter(t *testing.T) { 14 s := Filter([]int{0, 1, 2, 3}, func(v int) bool { 15 return v > 0 && v < 3 16 }) 17 Equal(t, len(s), 2) 18 Equal(t, s[0], 0) 19 Equal(t, s[1], 3) 20 21 } 22 23 func TestRetain(t *testing.T) { 24 s := Retain([]int{0, 1, 2, 3}, func(v int) bool { 25 return v > 0 && v < 3 26 }) 27 Equal(t, len(s), 2) 28 Equal(t, s[0], 1) 29 Equal(t, s[1], 2) 30 } 31 32 func TestMap(t *testing.T) { 33 s := Map[int, []string]([]int{0, 1, 2, 3}, make([]string, 0, 4), func(accum []string, v int) []string { 34 return append(accum, strconv.Itoa(v)) 35 }) 36 Equal(t, len(s), 4) 37 Equal(t, s[0], "0") 38 Equal(t, s[1], "1") 39 Equal(t, s[2], "2") 40 Equal(t, s[3], "3") 41 42 // Test Map empty slice 43 s2 := Map[int, []string](nil, nil, func(accum []string, v int) []string { 44 return append(accum, strconv.Itoa(v)) 45 }) 46 Equal(t, len(s2), 0) 47 } 48 49 func TestSort(t *testing.T) { 50 s := []int{0, 1, 2} 51 Sort(s, func(i int, j int) bool { 52 return i > j 53 }) 54 Equal(t, s[0], 2) 55 Equal(t, s[1], 1) 56 Equal(t, s[2], 0) 57 } 58 59 func TestSortStable(t *testing.T) { 60 s := []int{0, 1, 1, 2} 61 SortStable(s, func(i int, j int) bool { 62 return i > j 63 }) 64 Equal(t, s[0], 2) 65 Equal(t, s[1], 1) 66 Equal(t, s[2], 1) 67 Equal(t, s[3], 0) 68 } 69 70 func TestReduce(t *testing.T) { 71 result := Reduce([]int{0, 1, 2}, func(accum int, current int) int { 72 return accum + current 73 }) 74 Equal(t, result, optionext.Some(3)) 75 76 // Test Reduce empty slice 77 result = Reduce([]int{}, func(accum int, current int) int { 78 return accum + current 79 }) 80 Equal(t, result, optionext.None[int]()) 81 } 82 83 func TestReverse(t *testing.T) { 84 s := []int{1, 2} 85 Reverse(s) 86 Equal(t, []int{2, 1}, s) 87 88 s = []int{1, 2, 3} 89 Reverse(s) 90 Equal(t, []int{3, 2, 1}, s) 91 } 92 93 func BenchmarkReverse(b *testing.B) { 94 s := make([]int, 0, 1000) 95 for i := 0; i < 1000; i++ { 96 s = append(s, i) 97 } 98 b.ResetTimer() 99 for i := 0; i < b.N; i++ { 100 Reverse(s) 101 } 102 }