Skip to content

Commit

Permalink
Merge pull request #28 from arduino/feat/as-slice
Browse files Browse the repository at this point in the history
feat: map as slice
  • Loading branch information
Bikappa authored Feb 13, 2023
2 parents 66018f8 + b490683 commit ebf9cbb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 11 additions & 1 deletion properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,12 +485,22 @@ func (m *Map) Values() []string {
return values
}

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

// AsSlice returns the underlying map[string]string as a slice of
// strings with the pattern `{key}={value}`, maintaining the insertion order of the keys.
func (m *Map) AsSlice() []string {
properties := make([]string, len(m.o))
for i, key := range m.o {
properties[i] = strings.Join([]string{key, m.kv[key]}, "=")
}
return properties
}

// Clone makes a copy of the Map
func (m *Map) Clone() *Map {
clone := NewMap()
Expand Down
18 changes: 18 additions & 0 deletions properties_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,21 @@ func TestLoadingNonUTF8Properties(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "Aáa", m.Get("maintainer"))
}

func TestAsSlice(t *testing.T) {
emptyProperties := NewMap()
require.Len(t, emptyProperties.AsSlice(), 0)

properties := NewMap()
properties.Set("key1", "value1")
properties.Set("key2", "value2")
properties.Set("key3", "value3=somethingElse")

require.Len(t, properties.AsSlice(), properties.Size())

require.Equal(t, []string{
"key1=value1",
"key2=value2",
"key3=value3=somethingElse"},
properties.AsSlice())
}

0 comments on commit ebf9cbb

Please sign in to comment.