Skip to content

Commit

Permalink
Implement the marshaler interface so collections can be easily unmash…
Browse files Browse the repository at this point in the history
…aled into valid JSON
  • Loading branch information
wilhelm-murdoch committed Apr 1, 2022
1 parent 7ce437c commit 7e34f73
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions collection.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package collection

import (
"bytes"
"encoding/json"
"math/rand"
"reflect"
"time"
Expand Down Expand Up @@ -354,3 +356,16 @@ func (c *Collection[T]) CountBy(f func(T) bool) (count int) {
}
return
}

// MarshalJSON implements the Marshaler interface so the current collection's
// items can be marshalled into valid JSON.
func (c *Collection[T]) MarshalJSON() ([]byte, error) {
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)

if err := encoder.Encode(c.Items()); err != nil {
return nil, err
}

return buffer.Bytes(), nil
}

0 comments on commit 7e34f73

Please sign in to comment.