Skip to content

Commit

Permalink
adding key lookup with value helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Mzack9999 committed Feb 28, 2023
1 parent 24aa1ef commit 8b924a4
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
14 changes: 13 additions & 1 deletion maps/generic_map.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package mapsutil

// Map wraps a generic map type
type Map[K comparable, V any] map[K]V
type Map[K, V comparable] map[K]V

// Has checks if the current map has the provided key
func (m Map[K, V]) Has(key K) bool {
Expand Down Expand Up @@ -32,3 +32,15 @@ func (m Map[K, V]) Merge(n map[K]V) {
m[k] = v
}
}

// GetKeyWithValue returns the first key having value
func (m Map[K, V]) GetKeyWithValue(value V) (K, bool) {
var zero K
for k, v := range m {
if v == value {
return k, true
}
}

return zero, false
}
52 changes: 52 additions & 0 deletions maps/generic_map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package mapsutil
import (
"reflect"
"testing"

"github.com/stretchr/testify/require"
)

func TestMapHas(t *testing.T) {
Expand Down Expand Up @@ -66,3 +68,53 @@ func TestMapMerge(t *testing.T) {
t.Errorf("Merge(%v) = %v, expected %v", n, m, expected)
}
}

func TestMap_GetKeyWithValue(t *testing.T) {
type testCase[K, V comparable] struct {
InputMap Map[K, V]
Value V
ExpectedKey K
ExpectedOk bool
}

genericMap := Map[string, string]{"a": "a", "b": "b", "c": "c"}

testCases := []testCase[string, string]{
{
InputMap: genericMap,
Value: "b",
ExpectedKey: "b",
ExpectedOk: true,
},
{
InputMap: genericMap,
Value: "d",
ExpectedKey: "",
ExpectedOk: false,
},
{
InputMap: genericMap,
Value: "b",
ExpectedKey: "b",
ExpectedOk: true,
},
{
InputMap: genericMap,
Value: "d",
ExpectedKey: "",
ExpectedOk: false,
},
{
InputMap: genericMap,
Value: "value",
ExpectedKey: "",
ExpectedOk: false,
},
}

for _, tc := range testCases {
key, ok := tc.InputMap.GetKeyWithValue(tc.Value)
require.Equal(t, tc.ExpectedKey, key)
require.Equal(t, tc.ExpectedOk, ok)
}
}
2 changes: 1 addition & 1 deletion maps/synclock_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var (
)

// SyncLock adds sync and lock capabilities to generic map
type SyncLockMap[K comparable, V any] struct {
type SyncLockMap[K, V comparable] struct {
ReadOnly atomic.Bool
mu sync.RWMutex
Map Map[K, V]
Expand Down

0 comments on commit 8b924a4

Please sign in to comment.