Skip to content

Commit 40cde39

Browse files
committed
optimize tailing nil removal
1 parent 2a23c39 commit 40cde39

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

table/util.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,15 @@ func objAsSlice(in interface{}) []interface{} {
9292
}
9393

9494
// remove trailing nil pointers
95+
tailIdx := len(out)
9596
for i := len(out) - 1; i >= 0; i-- {
9697
val := reflect.ValueOf(out[i])
97-
if val.Kind() == reflect.Ptr && val.IsNil() {
98-
out = out[:i]
99-
} else {
98+
if val.Kind() != reflect.Ptr || !val.IsNil() {
10099
break
101100
}
101+
tailIdx = i
102102
}
103-
return out
103+
return out[:tailIdx]
104104
}
105105

106106
func objIsSlice(in interface{}) bool {

table/util_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ func Test_objAsSlice(t *testing.T) {
5858
assert.Equal(t, "[1 2 3]", fmt.Sprint(objAsSlice(&[]int{a, b, c})))
5959
assert.Equal(t, "[1 2 3]", fmt.Sprint(objAsSlice(&[]*int{&a, &b, &c})))
6060
assert.Equal(t, "[1 2]", fmt.Sprint(objAsSlice(&[]*int{&a, &b, nil})))
61+
assert.Equal(t, "[1]", fmt.Sprint(objAsSlice(&[]*int{&a, nil, nil})))
62+
assert.Equal(t, "[]", fmt.Sprint(objAsSlice(&[]*int{nil, nil, nil})))
6163
assert.Equal(t, "[<nil> 2]", fmt.Sprint(objAsSlice(&[]*int{nil, &b, nil})))
6264
}
6365

0 commit comments

Comments
 (0)