Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement funk.Nth #166

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}