Skip to content

Commit ebf9cbb

Browse files
authored
Merge pull request #28 from arduino/feat/as-slice
feat: map as slice
2 parents 66018f8 + b490683 commit ebf9cbb

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

properties.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -485,12 +485,22 @@ func (m *Map) Values() []string {
485485
return values
486486
}
487487

488-
// AsMap return the underlying map[string]string. This is useful if you need to
488+
// AsMap returns the underlying map[string]string. This is useful if you need to
489489
// for ... range but without the requirement of the ordered elements.
490490
func (m *Map) AsMap() map[string]string {
491491
return m.kv
492492
}
493493

494+
// AsSlice returns the underlying map[string]string as a slice of
495+
// strings with the pattern `{key}={value}`, maintaining the insertion order of the keys.
496+
func (m *Map) AsSlice() []string {
497+
properties := make([]string, len(m.o))
498+
for i, key := range m.o {
499+
properties[i] = strings.Join([]string{key, m.kv[key]}, "=")
500+
}
501+
return properties
502+
}
503+
494504
// Clone makes a copy of the Map
495505
func (m *Map) Clone() *Map {
496506
clone := NewMap()

properties_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -390,3 +390,21 @@ func TestLoadingNonUTF8Properties(t *testing.T) {
390390
require.NoError(t, err)
391391
require.Equal(t, "Aáa", m.Get("maintainer"))
392392
}
393+
394+
func TestAsSlice(t *testing.T) {
395+
emptyProperties := NewMap()
396+
require.Len(t, emptyProperties.AsSlice(), 0)
397+
398+
properties := NewMap()
399+
properties.Set("key1", "value1")
400+
properties.Set("key2", "value2")
401+
properties.Set("key3", "value3=somethingElse")
402+
403+
require.Len(t, properties.AsSlice(), properties.Size())
404+
405+
require.Equal(t, []string{
406+
"key1=value1",
407+
"key2=value2",
408+
"key3=value3=somethingElse"},
409+
properties.AsSlice())
410+
}

0 commit comments

Comments
 (0)