diff options
| author | Dave Henderson <dhenderson@gmail.com> | 2018-09-08 08:45:48 -0400 |
|---|---|---|
| committer | Dave Henderson <dhenderson@gmail.com> | 2018-09-08 09:08:07 -0400 |
| commit | 2e972e568ff52d3c4606ce2b6350c0e764f44e03 (patch) | |
| tree | b3ce11a3379e8eb940498a053c577d99c5500281 /conv | |
| parent | 2feda27f6a4aacdca921d78c2c327d923f74c618 (diff) | |
Adding dict/conv.Dict function
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
Diffstat (limited to 'conv')
| -rw-r--r-- | conv/conv.go | 19 | ||||
| -rw-r--r-- | conv/conv_test.go | 23 |
2 files changed, 42 insertions, 0 deletions
diff --git a/conv/conv.go b/conv/conv.go index 5db95976..442ba216 100644 --- a/conv/conv.go +++ b/conv/conv.go @@ -307,3 +307,22 @@ func ToFloat64s(in ...interface{}) []float64 { } return out } + +// Dict is a convenience function that creates a map with string keys. +// Provide arguments as key/value pairs. If an odd number of arguments +// is provided, the last is used as the key, and an empty string is +// set as the value. +// All keys are converted to strings, regardless of input type. +func Dict(v ...interface{}) (map[string]interface{}, error) { + dict := map[string]interface{}{} + lenv := len(v) + for i := 0; i < lenv; i += 2 { + key := ToString(v[i]) + if i+1 >= lenv { + dict[key] = "" + continue + } + dict[key] = v[i+1] + } + return dict, nil +} diff --git a/conv/conv_test.go b/conv/conv_test.go index d6c313c7..43bc6d80 100644 --- a/conv/conv_test.go +++ b/conv/conv_test.go @@ -262,3 +262,26 @@ func TestToBool(t *testing.T) { assert.False(t, ToBool("4,096")) assert.False(t, ToBool("-4,096.00")) } + +func TestDict(t *testing.T) { + testdata := []struct { + args []interface{} + expected map[string]interface{} + }{ + {nil, map[string]interface{}{}}, + {[]interface{}{}, map[string]interface{}{}}, + {[]interface{}{"foo"}, map[string]interface{}{"foo": ""}}, + {[]interface{}{42}, map[string]interface{}{"42": ""}}, + {[]interface{}{"foo", nil}, map[string]interface{}{"foo": nil}}, + {[]interface{}{"foo", "bar"}, map[string]interface{}{"foo": "bar"}}, + {[]interface{}{"foo", "bar", "baz", true}, map[string]interface{}{ + "foo": "bar", + "baz": true, + }}, + } + + for _, d := range testdata { + actual, _ := Dict(d.args...) + assert.Equal(t, d.expected, actual) + } +} |
