Skip to content

Commit

Permalink
Merge pull request #57 from olachat/yinloo/support-slice
Browse files Browse the repository at this point in the history
support slices in NewParams
  • Loading branch information
yinloo-ola authored Feb 2, 2024
2 parents 9735f8c + 0f6e3cf commit 3902eab
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
23 changes: 22 additions & 1 deletion coredb/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,28 @@ type Params struct {
}

func NewParams(params ...any) *Params {
return &Params{params}
totalLen := 0
for i := 0; i < len(params); i++ {
if v := reflect.ValueOf(params[i]); v.Kind() == reflect.Slice {
totalLen += v.Len()
} else {
totalLen++
}
}

newSlice := make([]any, 0, totalLen)
for i := 0; i < len(params); i++ {
if v := reflect.ValueOf(params[i]); v.Kind() == reflect.Slice {
// append all elements in params[0] to p.params
for j := 0; j < v.Len(); j++ {
newSlice = append(newSlice, v.Index(j).Interface())
}
} else {
newSlice = append(newSlice, params[i])
}
}

return &Params{params: newSlice}
}

func (p *Params) Add(params ...any) {
Expand Down
4 changes: 4 additions & 0 deletions coredb/params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,8 @@ func TestNewParams(t *testing.T) {
as.Equal(88, out[9])
as.Equal(99, out[10])
as.Equal(100, out[11])

p2 := NewParams(1, 2, []int{3, 4, 5}, "Mary", []string{"Wilson", "Mandy"})
p2.Get()
as.Equal([]any{1, 2, 3, 4, 5, "Mary", "Wilson", "Mandy"}, p2.Get())
}

0 comments on commit 3902eab

Please sign in to comment.