diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c70b8c0..bfd8e7d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,5 +1,8 @@ name: Go on: + pull_request: + branches: + - 'master' push: tags: - '*' diff --git a/map.go b/map.go index c490dbd..110bfcd 100644 --- a/map.go +++ b/map.go @@ -229,3 +229,15 @@ func MapDropKeys[M ~map[K]V, K comparable, V any](in M, keys ...K) { delete(in, keys[i]) } } + +// MapPopKeyDefault will return value for given key and delete this key from source map. +// In case of key do not presented in map - returns default value. +func MapPopKeyDefault[M ~map[K]V, K comparable, V any](in M, key K, def V) V { + val, ok := in[key] + if ok { + delete(in, key) + return val + } + + return def +} diff --git a/map_test.go b/map_test.go index ab3ca24..e0ef908 100644 --- a/map_test.go +++ b/map_test.go @@ -697,3 +697,26 @@ func TestMapDropKeys(t *testing.T) { }) } } + +func TestMapPopKeyDefault(t *testing.T) { + t.Parallel() + + f := func(in map[int]int, k, def, exp int) { + t.Helper() + t.Run("", func(t *testing.T) { + t.Parallel() + + res := just.MapPopKeyDefault(in, k, def) + require.Equal(t, exp, res) + require.False(t, just.MapContainsKey(in, k)) + }) + } + + type m map[int]int + const ne = -1 + + f(nil, 1, ne, ne) + f(m{}, 1, ne, ne) + f(m{1: 11}, 1, ne, 11) + f(m{2: 22}, 1, ne, ne) +}