From f530b38601cc479a96da7b75e9b8cc195818f190 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrea=20Funt=C3=B2?= Date: Wed, 3 May 2023 17:46:49 +0200 Subject: [PATCH] Add unt test for ElementAt --- scan.go | 25 ++++++++++++++++++++++++- scan_test.go | 15 +++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/scan.go b/scan.go index 197330f..110a635 100644 --- a/scan.go +++ b/scan.go @@ -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)) @@ -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())) } diff --git a/scan_test.go b/scan_test.go index 8fc8faf..9134183 100644 --- a/scan_test.go +++ b/scan_test.go @@ -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)