Skip to content

Commit 8b924a4

Browse files
committed
adding key lookup with value helper
1 parent 24aa1ef commit 8b924a4

3 files changed

Lines changed: 66 additions & 2 deletions

File tree

maps/generic_map.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package mapsutil
22

33
// Map wraps a generic map type
4-
type Map[K comparable, V any] map[K]V
4+
type Map[K, V comparable] map[K]V
55

66
// Has checks if the current map has the provided key
77
func (m Map[K, V]) Has(key K) bool {
@@ -32,3 +32,15 @@ func (m Map[K, V]) Merge(n map[K]V) {
3232
m[k] = v
3333
}
3434
}
35+
36+
// GetKeyWithValue returns the first key having value
37+
func (m Map[K, V]) GetKeyWithValue(value V) (K, bool) {
38+
var zero K
39+
for k, v := range m {
40+
if v == value {
41+
return k, true
42+
}
43+
}
44+
45+
return zero, false
46+
}

maps/generic_map_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package mapsutil
33
import (
44
"reflect"
55
"testing"
6+
7+
"github.com/stretchr/testify/require"
68
)
79

810
func TestMapHas(t *testing.T) {
@@ -66,3 +68,53 @@ func TestMapMerge(t *testing.T) {
6668
t.Errorf("Merge(%v) = %v, expected %v", n, m, expected)
6769
}
6870
}
71+
72+
func TestMap_GetKeyWithValue(t *testing.T) {
73+
type testCase[K, V comparable] struct {
74+
InputMap Map[K, V]
75+
Value V
76+
ExpectedKey K
77+
ExpectedOk bool
78+
}
79+
80+
genericMap := Map[string, string]{"a": "a", "b": "b", "c": "c"}
81+
82+
testCases := []testCase[string, string]{
83+
{
84+
InputMap: genericMap,
85+
Value: "b",
86+
ExpectedKey: "b",
87+
ExpectedOk: true,
88+
},
89+
{
90+
InputMap: genericMap,
91+
Value: "d",
92+
ExpectedKey: "",
93+
ExpectedOk: false,
94+
},
95+
{
96+
InputMap: genericMap,
97+
Value: "b",
98+
ExpectedKey: "b",
99+
ExpectedOk: true,
100+
},
101+
{
102+
InputMap: genericMap,
103+
Value: "d",
104+
ExpectedKey: "",
105+
ExpectedOk: false,
106+
},
107+
{
108+
InputMap: genericMap,
109+
Value: "value",
110+
ExpectedKey: "",
111+
ExpectedOk: false,
112+
},
113+
}
114+
115+
for _, tc := range testCases {
116+
key, ok := tc.InputMap.GetKeyWithValue(tc.Value)
117+
require.Equal(t, tc.ExpectedKey, key)
118+
require.Equal(t, tc.ExpectedOk, ok)
119+
}
120+
}

maps/synclock_map.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ var (
1111
)
1212

1313
// SyncLock adds sync and lock capabilities to generic map
14-
type SyncLockMap[K comparable, V any] struct {
14+
type SyncLockMap[K, V comparable] struct {
1515
ReadOnly atomic.Bool
1616
mu sync.RWMutex
1717
Map Map[K, V]

0 commit comments

Comments
 (0)