Skip to content

Commit

Permalink
feat: Implement funk.Nth
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenvantuan2391996 committed Aug 7, 2023
1 parent 045ef11 commit 148b774
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
28 changes: 28 additions & 0 deletions nth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package funk

import (
"reflect"
)

// Nth returns the element at the specified index from the array (Slice).
// The index is 1-based, so the first element is at index 1.
func Nth(in interface{}, number int) interface{} {
if !IsCollection(in) {
panic("First parameter must be a collection")
}

inValue := reflect.ValueOf(in)

if number >= inValue.Len() {
return nil
}

if number < 0 {
if number+inValue.Len() < 0 {
return nil
}
number = number + inValue.Len()
}

return inValue.Index(number).Interface()
}
61 changes: 61 additions & 0 deletions nth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package funk

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test_nth_valid_n_great_than_array_length(t *testing.T) {
result := Nth([]int{1, 2, 3}, 4)

assert.Equal(t, nil, result)
}

func Test_nth_valid_n_less_than_zero_one(t *testing.T) {
result := Nth([]int32{1, 2, 3}, -3)

assert.Equal(t, int32(1), result)
}

func Test_nth_valid_n_less_than_zero_two(t *testing.T) {
result := Nth([]int32{1, 2, 3}, -4)

assert.Equal(t, nil, result)
}

func Test_nth_valid_int64(t *testing.T) {
result := Nth([]int64{1, 2, 3}, 2)

assert.Equal(t, int64(3), result)
}

func Test_nth_valid_float32(t *testing.T) {
result := Nth([]float32{1, 2, 3}, 1)

assert.Equal(t, float32(2), result)
}

func Test_nth_valid_float64(t *testing.T) {
result := Nth([]float64{1.1, 2.2, 3.3}, 2)

assert.Equal(t, 3.3, result)
}

func Test_nth_valid_bool(t *testing.T) {
result := Nth([]bool{true, true, true, false, true}, 2)

assert.Equal(t, true, result)
}

func Test_nth_valid_string(t *testing.T) {
result := Nth([]string{"a", "b", "c", "d"}, -2)

assert.Equal(t, "c", result)
}

func Test_nth_valid_interface(t *testing.T) {
result := Nth([]interface{}{"1.1", true, 2.2, float32(3.3)}, 2)

assert.Equal(t, 2.2, result)
}

0 comments on commit 148b774

Please sign in to comment.