Skip to content

Commit 2689f46

Browse files
authored
Add function to convert key=value slice pairs to map (#71)
1 parent 3f0ebb8 commit 2689f46

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

collections/maps.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package collections
33
import (
44
"fmt"
55
"sort"
6+
"strings"
67
)
78

89
const (
@@ -53,3 +54,25 @@ func KeyValueStringSliceWithFormat(m map[string]string, format string) []string
5354

5455
return out
5556
}
57+
58+
// KeyValueStringSliceAsMap converts a string slice with key=value items into a map of slice values. The slice will
59+
// contain more than one item if a key is repeated in the string slice list.
60+
func KeyValueStringSliceAsMap(kvPairs []string) map[string][]string {
61+
out := make(map[string][]string)
62+
for _, kvPair := range kvPairs {
63+
x := strings.Split(kvPair, "=")
64+
key := x[0]
65+
66+
var value string
67+
if len(x) > 1 {
68+
value = strings.Join(x[1:], "=")
69+
}
70+
71+
if _, hasKey := out[key]; hasKey {
72+
out[key] = append(out[key], value)
73+
} else {
74+
out[key] = []string{value}
75+
}
76+
}
77+
return out
78+
}

collections/maps_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,57 @@ func TestKeyValueStringSliceWithFormat(t *testing.T) {
179179
})
180180
}
181181
}
182+
183+
func TestKeyValueStringSliceAsMap(t *testing.T) {
184+
t.Parallel()
185+
186+
testCases := []struct {
187+
name string
188+
input []string
189+
expected map[string][]string
190+
}{
191+
{
192+
"BaseCase",
193+
[]string{"key=value"},
194+
map[string][]string{"key": []string{"value"}},
195+
},
196+
{"EmptyCase", []string{}, map[string][]string{}},
197+
{
198+
"RepeatedKey",
199+
[]string{"key=valueA", "foo=bar", "key=valueB"},
200+
map[string][]string{
201+
"key": []string{"valueA", "valueB"},
202+
"foo": []string{"bar"},
203+
},
204+
},
205+
{
206+
"EmptyValue",
207+
[]string{"key", "foo=", "foo=baz"},
208+
map[string][]string{
209+
"key": []string{""},
210+
"foo": []string{"", "baz"},
211+
},
212+
},
213+
{
214+
"EqualInValue",
215+
[]string{"key=foo=bar"},
216+
map[string][]string{
217+
"key": []string{"foo=bar"},
218+
},
219+
},
220+
{
221+
"EmptyString",
222+
[]string{""},
223+
map[string][]string{
224+
"": []string{""},
225+
},
226+
},
227+
}
228+
229+
for _, testCase := range testCases {
230+
t.Run(testCase.name, func(t *testing.T) {
231+
actual := KeyValueStringSliceAsMap(testCase.input)
232+
assert.Equal(t, testCase.expected, actual)
233+
})
234+
}
235+
}

0 commit comments

Comments
 (0)