on main help sign in
feat(csync.Map): added GetOrSet

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

commit1e47f4eda8772536b63ef866209e65b6b81cae37 authorCarlos Alexandro Becker <caarlos0@users.noreply.github.com> dateThu 7 Aug 2025, 14:01 (1 year ago) parent9719451
2 files changed+22
internal/csync/maps.go+12 internal/csync/maps_test.go+10
internal/csync/maps.go+12
@@ -56,6 +56,18 @@ func (m *Map[K, V]) Len() int {
5656 return len(m.inner)
5757}
5858
59+// GetOrSet gets and returns the key if it exists, otherwise, it executes the
60+// given function, set its return value for the given key, and returns it.
61+func (m *Map[K, V]) GetOrSet(key K, fn func() V) V {
62+ got, ok := m.Get(key)
63+ if ok {
64+ return got
65+ }
66+ value := fn()
67+ m.Set(key, value)
68+ return value
69+}
70+
5971// Take gets an item and then deletes it.
6072func (m *Map[K, V]) Take(key K) (V, bool) {
6173 m.mu.Lock()
internal/csync/maps_test.go+10
@@ -54,6 +54,16 @@ func TestMap_Set(t *testing.T) {
5454 require.Equal(t, 1, m.Len())
5555}
5656
57+func TestMap_GetOrSet(t *testing.T) {
58+ t.Parallel()
59+
60+ m := NewMap[string, int]()
61+
62+ require.Equal(t, 42, m.GetOrSet("key1", func() int { return 42 }))
63+ require.Equal(t, 42, m.GetOrSet("key1", func() int { return 99999 }))
64+ require.Equal(t, 1, m.Len())
65+}
66+
5767func TestMap_Get(t *testing.T) {
5868 t.Parallel()
5969