Added generics to Collection
This commit is contained in:
parent
adce06420c
commit
309f03ba40
@ -2,41 +2,39 @@ package ocean
|
|||||||
|
|
||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
type Collection interface {
|
type Collection[T any] interface {
|
||||||
Get(key string) (value any, ok bool)
|
Get(key string) (value T, ok bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
// collection is a hash map of homogeneous data.
|
// collection is a hash map of homogeneous data.
|
||||||
type collection struct {
|
type collection[T any] struct {
|
||||||
data sync.Map
|
data sync.Map
|
||||||
name string
|
name string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Force interface implementation
|
|
||||||
var _ Collection = (*collection)(nil)
|
|
||||||
|
|
||||||
// NewCollection creates a new collection with the given name.
|
// NewCollection creates a new collection with the given name.
|
||||||
func NewCollection(name string) *collection {
|
func NewCollection[T any](name string) *collection[T] {
|
||||||
return &collection{name: name}
|
return &collection[T]{name: name}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the value for the given key.
|
// Get returns the value for the given key.
|
||||||
func (c *collection) Get(key string) (value any, ok bool) {
|
func (c *collection[T]) Get(key string) (T, bool) {
|
||||||
return c.data.Load(key)
|
value, exists := c.data.Load(key)
|
||||||
|
return value.(T), exists
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set sets the value for the given key.
|
// Set sets the value for the given key.
|
||||||
func (c *collection) Set(key string, value any) {
|
func (c *collection[T]) Set(key string, value T) {
|
||||||
c.data.Store(key, value)
|
c.data.Store(key, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes a key from the collection.
|
// Delete deletes a key from the collection.
|
||||||
func (c *collection) Delete(key string) {
|
func (c *collection[T]) Delete(key string) {
|
||||||
c.data.Delete(key)
|
c.data.Delete(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exists returns whether or not the key exists.
|
// Exists returns whether or not the key exists.
|
||||||
func (c *collection) Exists(key string) bool {
|
func (c *collection[T]) Exists(key string) bool {
|
||||||
_, exists := c.data.Load(key)
|
_, exists := c.data.Load(key)
|
||||||
return exists
|
return exists
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestNewCollection(t *testing.T) {
|
func TestNewCollection(t *testing.T) {
|
||||||
users := ocean.NewCollection("User")
|
users := ocean.NewCollection[string]("User")
|
||||||
|
|
||||||
assert.False(t, users.Exists("Hello"))
|
assert.False(t, users.Exists("Hello"))
|
||||||
assert.False(t, users.Exists("World"))
|
assert.False(t, users.Exists("World"))
|
||||||
|
Loading…
Reference in New Issue
Block a user