Skip to content

Commit

Permalink
Add MapPopKeyDefault
Browse files Browse the repository at this point in the history
  • Loading branch information
kazhuravlev authored Dec 3, 2023
2 parents 622c349 + 6c0b234 commit 8a7ed4f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
name: Go
on:
pull_request:
branches:
- 'master'
push:
tags:
- '*'
Expand Down
12 changes: 12 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
23 changes: 23 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 8a7ed4f

Please sign in to comment.