From 40cde392126a986413b1689ccb4a6bc1c4f9f80b Mon Sep 17 00:00:00 2001 From: Naveen Mahalingam Date: Wed, 27 Nov 2024 12:12:24 -0800 Subject: [PATCH] optimize tailing nil removal --- table/util.go | 8 ++++---- table/util_test.go | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/table/util.go b/table/util.go index 1b2141e..6b7a658 100644 --- a/table/util.go +++ b/table/util.go @@ -92,15 +92,15 @@ func objAsSlice(in interface{}) []interface{} { } // remove trailing nil pointers + tailIdx := len(out) for i := len(out) - 1; i >= 0; i-- { val := reflect.ValueOf(out[i]) - if val.Kind() == reflect.Ptr && val.IsNil() { - out = out[:i] - } else { + if val.Kind() != reflect.Ptr || !val.IsNil() { break } + tailIdx = i } - return out + return out[:tailIdx] } func objIsSlice(in interface{}) bool { diff --git a/table/util_test.go b/table/util_test.go index af9d6fc..d176bca 100644 --- a/table/util_test.go +++ b/table/util_test.go @@ -58,6 +58,8 @@ func Test_objAsSlice(t *testing.T) { assert.Equal(t, "[1 2 3]", fmt.Sprint(objAsSlice(&[]int{a, b, c}))) assert.Equal(t, "[1 2 3]", fmt.Sprint(objAsSlice(&[]*int{&a, &b, &c}))) assert.Equal(t, "[1 2]", fmt.Sprint(objAsSlice(&[]*int{&a, &b, nil}))) + assert.Equal(t, "[1]", fmt.Sprint(objAsSlice(&[]*int{&a, nil, nil}))) + assert.Equal(t, "[]", fmt.Sprint(objAsSlice(&[]*int{nil, nil, nil}))) assert.Equal(t, "[ 2]", fmt.Sprint(objAsSlice(&[]*int{nil, &b, nil}))) }