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

Enable retrieval of element in array/slice which is neither head nor tail. #163

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
25 changes: 24 additions & 1 deletion scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,29 @@ func Last(arr interface{}) interface{} {
panic(fmt.Sprintf("Type %s is not supported by Last", valueType.String()))
}

// ElementAt gets the element of array at the given index.
func ElementAt(arr interface{}, index int) interface{} {
value := redirectValue(reflect.ValueOf(arr))
valueType := value.Type()

kind := value.Kind()

if kind == reflect.Array || kind == reflect.Slice {
if value.Len() == 0 {
return nil
}

if index < 0 || index >= value.Len() {
// maybe panic?
return nil
}

return value.Index(index).Interface()
}

panic(fmt.Sprintf("Type %s is not supported by ElementAt", valueType.String()))
}

// Initial gets all but the last element of array.
func Initial(arr interface{}) interface{} {
value := redirectValue(reflect.ValueOf(arr))
Expand Down Expand Up @@ -201,5 +224,5 @@ func Tail(arr interface{}) interface{} {
return value.Slice(1, length).Interface()
}

panic(fmt.Sprintf("Type %s is not supported by Initial", valueType.String()))
panic(fmt.Sprintf("Type %s is not supported by Tail", valueType.String()))
}
15 changes: 15 additions & 0 deletions scan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,21 @@ func TestLast(t *testing.T) {
is.Equal(Last([]int{1, 2, 3, 4}), 4)
}

func TestElementAt(t *testing.T) {
is := assert.New(t)

for k, v := range map[int]interface{}{
-1: nil,
0: 1,
1: 2,
2: 3,
3: 4,
5: nil,
} {
is.Equal(ElementAt([]int{1, 2, 3, 4}, k), v)
}
}

func TestTail(t *testing.T) {
is := assert.New(t)

Expand Down