Skip to content

Commit

Permalink
minor revise params
Browse files Browse the repository at this point in the history
  • Loading branch information
CMGS committed Feb 3, 2023
1 parent ced5c87 commit 182c49b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 17 deletions.
41 changes: 25 additions & 16 deletions types/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,12 @@ func (r RawParams) Float64(key string) float64 {

// Int64 .
func (r RawParams) Int64(key string) int64 {
if !r.IsSet(key) {
return int64(0)
}
var str string
if f, ok := r[key].(float64); ok {
str = fmt.Sprintf("%.0f", f)
} else {
str = fmt.Sprintf("%+v", r[key])
}
res, _ := strconv.ParseInt(str, 10, 64)
return res
return intHelper[int64](r, key)
}

// Int .
func (r RawParams) Int(key string) int {
return intHelper[int](r, key)
}

// String .
Expand Down Expand Up @@ -107,17 +102,31 @@ func sliceHelper[T any](r RawParams, key string) []T {
}
var res []T
if s, ok := r[key].([]interface{}); ok {
res = make([]T, len(s))
for i, v := range s {
res = []T{}
for _, v := range s {
if r, ok := v.(T); ok {
res[i] = r
} else {
return nil
res = append(res, r)
// } else {
// return nil // TODO why continue?
}
}
}
return res
}

func intHelper[T int | int64](r RawParams, key string) T {
if !r.IsSet(key) {
return T(0)
}
var str string
if f, ok := r[key].(float64); ok {
str = fmt.Sprintf("%.0f", f)
} else {
str = fmt.Sprintf("%+v", r[key])
}
res, _ := strconv.ParseInt(str, 10, 64)
return T(res)
}

// Resources all cosmos use this
type Resources map[string]*RawParams
2 changes: 1 addition & 1 deletion types/resource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func TestRawParams(t *testing.T) {
assert.Equal(t, r.String("cde"), "")
assert.Len(t, r.StringSlice("bef"), 1)
assert.Nil(t, r.OneOfStringSlice("efg"))
assert.Len(t, *r.RawParams("fgd"), 0)
assert.Nil(t, r.RawParams("fgd"))

r = RawParams{
"int64": 1,
Expand Down

0 comments on commit 182c49b

Please sign in to comment.