github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xslice/slice_test.go (about)

     1  package xslice
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  
     9  	"github.com/go-board/x-go/xsort"
    10  )
    11  
    12  func TestSliceTransform(t *testing.T) {
    13  	t.Run("map", func(t *testing.T) {
    14  		require.EqualValues(t, []interface{}{"11", "22", "33"}, Map([]interface{}{"1", "2", "3"}, func(v interface{}) interface{} {
    15  			return strings.Repeat(v.(string), 2)
    16  		}), "map produce another slice with all of it's value string repeated two times")
    17  	})
    18  
    19  	t.Run("filter", func(t *testing.T) {
    20  		require.Equal(t, 2, len(Filter([]interface{}{1, 2, 3}, func(v interface{}) bool {
    21  			return v.(int)%2 == 1
    22  		})), "filter produce another slice with length 2")
    23  		require.EqualValues(t, []interface{}{1, 3}, Filter([]interface{}{1, 2, 3}, func(v interface{}) bool {
    24  			return v.(int)%2 == 1
    25  		}), "filter produce another slice with two elements")
    26  	})
    27  
    28  	t.Run("fold", func(t *testing.T) {
    29  		t.Run("left", func(t *testing.T) {
    30  			require.Equal(t, -6, FoldLeft([]interface{}{1, 2, 3}, func(left, right interface{}) interface{} {
    31  				return left.(int) - right.(int)
    32  			}, 0), "fold left produce -6")
    33  		})
    34  		t.Run("right", func(t *testing.T) {
    35  			require.Equal(t, 0, FoldRight([]interface{}{1, 2, 3}, func(left, right interface{}) interface{} {
    36  				return left.(int) - right.(int)
    37  			}, 6), "fold left produce 0")
    38  		})
    39  	})
    40  }
    41  
    42  func TestUniqueSlice(t *testing.T) {
    43  	t.Run("int slice", func(t *testing.T) {
    44  		x := xsort.IntSlice(UniqueIntSlice([]int{1, 2, 3, 1, 2, 3}))
    45  		x.Sort()
    46  		require.EqualValues(t, []int{1, 2, 3}, x, "unique int slice produce []int{1,2,3,}")
    47  	})
    48  }
    49  
    50  func TestFunc(t *testing.T) {
    51  }