Skip to content

feat: map as slice #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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())
}