added Store.SetFunc method

This commit is contained in:
Gani Georgiev
2025-02-11 13:12:19 +02:00
parent 5c41938cb9
commit aaa3d67659
4 changed files with 4343 additions and 4273 deletions
+24 -1
View File
@@ -136,7 +136,7 @@ func (s *Store[K, T]) Values() []T {
return values
}
// Set sets (or overwrite if already exist) a new value for key.
// Set sets (or overwrite if already exists) a new value for key.
func (s *Store[K, T]) Set(key K, value T) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -148,6 +148,29 @@ func (s *Store[K, T]) Set(key K, value T) {
s.data[key] = value
}
// SetFunc sets (or overwrite if already exists) a new value resolved
// from the function callback for the provided key.
//
// The function callback receives as argument the old store element value (if exists).
// If there is no old store element, the argument will be the T zero value.
//
// Example:
//
// s := store.New[string, int](nil)
// s.SetFunc("count", func(old int) int {
// return old + 1
// })
func (s *Store[K, T]) SetFunc(key K, fn func(old T) T) {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = make(map[K]T)
}
s.data[key] = fn(s.data[key])
}
// GetOrSet retrieves a single existing value for the provided key
// or stores a new one if it doesn't exist.
func (s *Store[K, T]) GetOrSet(key K, setFunc func() T) T {
+26
View File
@@ -249,6 +249,32 @@ func TestSet(t *testing.T) {
}
}
func TestSetFunc(t *testing.T) {
s := store.Store[string, int]{}
// non existing value
s.SetFunc("test", func(old int) int {
if old != 0 {
t.Fatalf("Expected old value %d, got %d", 0, old)
}
return old + 2
})
if v := s.Get("test"); v != 2 {
t.Fatalf("Expected the stored value to be %d, got %d", 2, v)
}
// increment existing value
s.SetFunc("test", func(old int) int {
if old != 2 {
t.Fatalf("Expected old value %d, got %d", 2, old)
}
return old + 1
})
if v := s.Get("test"); v != 3 {
t.Fatalf("Expected the stored value to be %d, got %d", 3, v)
}
}
func TestGetOrSet(t *testing.T) {
s := store.New(map[string]int{
"test1": 0,