Skip to content

Commit

Permalink
PR #21: Add Map() and FilterFunc()
Browse files Browse the repository at this point in the history
* Map() exports the properties as a map[string]string.
* FilterFunc() allows filtering through a boolean function.
  • Loading branch information
Anirudh Vyas authored and magiconair committed Mar 20, 2017
1 parent 0d05d44 commit 91acf99
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
24 changes: 24 additions & 0 deletions properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,30 @@ func (p *Properties) WriteComment(w io.Writer, prefix string, enc Encoding) (n i
return
}

// Map returns a copy of the properties as a map.
func (p *Properties) Map() map[string]string {
m := make(map[string]string)
for k, v := range p.m {
m[k] = v
}
return m
}

// FilterFunc returns a copy of the properties which includes the values which passed all filters.
func (p *Properties) FilterFunc(filters ...func(k, v string) bool) *Properties {
pp := NewProperties()
outer:
for k, v := range p.m {
for _, f := range filters {
if !f(k, v) {
continue outer
}
pp.Set(k, v)
}
}
return pp
}

// ----------------------------------------------------------------------------

// Delete removes the key and its comments.
Expand Down
17 changes: 17 additions & 0 deletions properties_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,23 @@ func TestMerge(t *testing.T) {
assert.Equal(t, p1.GetComment("key"), "another comment")
}

func TestMap(t *testing.T) {
input := "key=value\nabc=def"
p := mustParse(t, input)
m := map[string]string{"key": "value", "abc": "def"}
assert.Equal(t, p.Map(), m)
}

func TestFilterFunc(t *testing.T) {
input := "key=value\nabc=def"
p := mustParse(t, input)
pp := p.FilterFunc(func(k, v string) bool {
return k != "abc"
})
m := map[string]string{"key": "value"}
assert.Equal(t, pp.Map(), m)
}

// ----------------------------------------------------------------------------

// tests all combinations of delimiters, leading and/or trailing whitespace and newlines.
Expand Down

0 comments on commit 91acf99

Please sign in to comment.