Skip to content

Commit b35e7f2

Browse files
Feature: add values and keys methods to sync.Map
1 parent a4e34a2 commit b35e7f2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

pkg/sync/map.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,23 @@ func (m *Map[K, V]) Len() int {
6767
defer m.mx.RUnlock()
6868
return len(m.m)
6969
}
70+
71+
func (m *Map[K, V]) Values() []V {
72+
arr := make([]V, 0)
73+
m.mx.RLock()
74+
for _, v := range m.m {
75+
arr = append(arr, v)
76+
}
77+
m.mx.RUnlock()
78+
return arr
79+
}
80+
81+
func (m *Map[K, V]) Keys() []K {
82+
arr := make([]K, 0)
83+
m.mx.RLock()
84+
for k := range m.m {
85+
arr = append(arr, k)
86+
}
87+
m.mx.RUnlock()
88+
return arr
89+
}

pkg/sync/map_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"runtime"
66
"sync"
77
"testing"
8+
9+
"github.com/stretchr/testify/require"
810
)
911

1012
func TestMap_Get(t *testing.T) {
@@ -170,3 +172,29 @@ func TestMap_Len(t *testing.T) {
170172
t.Fatalf("unexpected map size, got %v want %v", length, 3)
171173
}
172174
}
175+
176+
func TestMap_Values(t *testing.T) {
177+
m := NewMap[int, string]()
178+
for i, v := range [3]string{"len", "sync", "map"} {
179+
m.Set(i, v)
180+
}
181+
182+
values := m.Values()
183+
require.Len(t, values, 3)
184+
require.Contains(t, values, "len")
185+
require.Contains(t, values, "sync")
186+
require.Contains(t, values, "map")
187+
}
188+
189+
func TestMap_Keys(t *testing.T) {
190+
m := NewMap[int, string]()
191+
for i, v := range [3]string{"len", "sync", "map"} {
192+
m.Set(i, v)
193+
}
194+
195+
keys := m.Keys()
196+
require.Len(t, keys, 3)
197+
require.Contains(t, keys, 0)
198+
require.Contains(t, keys, 1)
199+
require.Contains(t, keys, 2)
200+
}

0 commit comments

Comments
 (0)