Code cleanup

This commit is contained in:
Dane Everitt
2020-04-10 18:03:35 -07:00
parent c57708d1e0
commit af241f3de4
5 changed files with 17 additions and 56 deletions

View File

@@ -4,14 +4,13 @@ import "sync"
type Collection struct {
items []*Server
mutex *sync.Mutex
sync.RWMutex
}
// Create a new collection from a slice of servers.
func NewCollection(servers []*Server) *Collection {
return &Collection{
items: servers,
mutex: &sync.Mutex{},
}
}
@@ -22,16 +21,15 @@ func (c *Collection) All() []*Server {
// Adds an item to the collection store.
func (c *Collection) Add(s *Server) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.Lock()
c.items = append(c.items, s)
c.Unlock()
}
// Returns only those items matching the filter criteria.
func (c *Collection) Filter(filter func(*Server) bool) []*Server {
c.mutex.Lock()
defer c.mutex.Unlock()
c.RLock()
defer c.RUnlock()
r := make([]*Server, 0)
for _, v := range c.items {
@@ -46,6 +44,9 @@ func (c *Collection) Filter(filter func(*Server) bool) []*Server {
// Returns a single element from the collection matching the filter. If nothing is
// found a nil result is returned.
func (c *Collection) Find(filter func(*Server) bool) *Server {
c.RLock()
defer c.RUnlock()
for _, v := range c.items {
if filter(v) {
return v
@@ -57,8 +58,8 @@ func (c *Collection) Find(filter func(*Server) bool) *Server {
// Removes all items from the collection that match the filter function.
func (c *Collection) Remove(filter func(*Server) bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.Lock()
defer c.Unlock()
r := make([]*Server, 0)
for _, v := range c.items {