diff --git a/array/tail.go b/array/tail.go new file mode 100644 index 0000000..3c3dcfc --- /dev/null +++ b/array/tail.go @@ -0,0 +1,29 @@ +package array + +import ( + "reflect" + + "github.com/warriors-vn/go-dash/constants" +) + +// tail returns a new slice containing all elements of the input array except the first one. +// It takes an array-like data structure as input and returns a new slice excluding the first element. +// The function returns the new slice and an error if any occurs. +func tail(array interface{}) (interface{}, error) { + arrValue := reflect.ValueOf(array) + + if arrValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array { + return nil, constants.ErrNotSlice + } + + if arrValue.Len() == 0 { + return array, nil + } + + result := reflect.MakeSlice(arrValue.Type(), 0, 0) + for i := 1; i < arrValue.Len(); i++ { + result = reflect.Append(result, arrValue.Index(i)) + } + + return result.Interface(), nil +} diff --git a/array/tail_test.go b/array/tail_test.go new file mode 100644 index 0000000..6f601ce --- /dev/null +++ b/array/tail_test.go @@ -0,0 +1,64 @@ +package array + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/warriors-vn/go-dash/constants" +) + +func Test_tail_valid_int(t *testing.T) { + result, err := tail([]int{1, 2, 3, 3, 2, 1}) + + assert.Equal(t, []int{2, 3, 3, 2, 1}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_int64(t *testing.T) { + result, err := tail([]int64{1, 2, 3, 3, 2, 1}) + + assert.Equal(t, []int64{2, 3, 3, 2, 1}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_float64(t *testing.T) { + result, err := tail([]float64{1.1, 2.2, 3.3, 3.3, 2.2, 1.1}) + + assert.Equal(t, []float64{2.2, 3.3, 3.3, 2.2, 1.1}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_string(t *testing.T) { + result, err := tail([]string{"1.1", "2.2", "3.3", "3.3", "2.2", "1.1"}) + + assert.Equal(t, []string{"2.2", "3.3", "3.3", "2.2", "1.1"}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_bool(t *testing.T) { + result, err := tail([]bool{false, true, true}) + + assert.Equal(t, []bool{true, true}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_interface(t *testing.T) { + result, err := tail([]interface{}{false, "true", true, 1, 2.2}) + + assert.Equal(t, []interface{}{"true", true, 1, 2.2}, result) + assert.Nil(t, err) +} + +func Test_tail_valid_array_empty(t *testing.T) { + result, err := tail([]bool{}) + + assert.Equal(t, []bool{}, result) + assert.Nil(t, err) +} + +func Test_tail_invalid_array_not_slice(t *testing.T) { + result, err := tail(true) + + assert.Equal(t, nil, result) + assert.Equal(t, constants.ErrNotSlice, err) +}