From 6e5ec0583c83b3d97b001beb8598c91a01d37139 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20D=C3=B6ll?= Date: Fri, 25 Oct 2024 20:26:40 +0000 Subject: [PATCH] feat: add exists map --- mapx/mapx.go | 6 ++++++ mapx/mapx_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+) 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)) +}