From 3ad142d5d759d0e0cb637a9294461b1f6d6e7eec Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 30 Mar 2022 19:41:55 +0800 Subject: [PATCH] feat: add ForEach func --- maputil/map.go | 7 +++++++ maputil/map_test.go | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/maputil/map.go b/maputil/map.go index 98f803c..58858a2 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -38,3 +38,10 @@ func Merge[K comparable, V any](maps ...map[K]V) map[K]V { return res } + +// ForEach executes iteratee funcation for every key and value pair in map +func ForEach[K comparable, V any](m map[K]V, iteratee func(key K, value V)) { + for k, v := range m { + iteratee(k, v) + } +} diff --git a/maputil/map_test.go b/maputil/map_test.go index 54259f1..c32e9a5 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -62,3 +62,22 @@ func TestMerge(t *testing.T) { assert.Equal(expected, acturl) } + +func TestForEach(t *testing.T) { + assert := internal.NewAssert(t, "TestForEach") + + m := map[string]int{ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + } + + var sum int + + ForEach(m, func(_ string, value int) { + sum += value + }) + + assert.Equal(10, sum) +}