From 2e972e568ff52d3c4606ce2b6350c0e764f44e03 Mon Sep 17 00:00:00 2001 From: Dave Henderson Date: Sat, 8 Sep 2018 08:45:48 -0400 Subject: Adding dict/conv.Dict function Signed-off-by: Dave Henderson --- conv/conv.go | 19 +++++++++++++++++++ conv/conv_test.go | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) (limited to 'conv') 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) + } +} -- cgit v1.2.3