diff --git a/mapx/mapx.go b/mapx/mapx.go index 4019ec1..8183b1b 100644 --- a/mapx/mapx.go +++ b/mapx/mapx.go @@ -19,3 +19,9 @@ func Keep[T1 comparable, T2 any](m map[T1]T2, keys ...T1) { } } } + +// Exists checks if a key exists in a map. +func Exists[T1 comparable, T2 any](m map[T1]T2, key T1) bool { + _, ok := m[key] + return ok +} diff --git a/mapx/mapx_test.go b/mapx/mapx_test.go index 5a7f58b..1c4bfad 100644 --- a/mapx/mapx_test.go +++ b/mapx/mapx_test.go @@ -32,3 +32,13 @@ func TestKeep(t *testing.T) { 2: "two", }, m) } + +func TestExists(t *testing.T) { + m := map[int]string{ + 1: "one", + 2: "two", + 3: "three", + } + assert.True(t, mapx.Exists(m, 2)) + assert.False(t, mapx.Exists(m, 4)) +}