Skip to content

Commit

Permalink
Merge pull request #92 from warriors-vn/dev-feature
Browse files Browse the repository at this point in the history
feat: add the func tail
  • Loading branch information
nguyenvantuan2391996 authored Aug 6, 2023
2 parents a1f2a8c + 8ba3b6e commit 5e708ae
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
29 changes: 29 additions & 0 deletions array/tail.go
Original file line number Diff line number Diff line change
@@ -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
}
64 changes: 64 additions & 0 deletions array/tail_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 5e708ae

Please sign in to comment.