Skip to content

Commit a3fbd68

Browse files
authored
Merge pull request #4 from vatsalpatel/map_functions
Implement GetOrDefault
2 parents 1af98eb + d809b24 commit a3fbd68

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

maps.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
package ut
22

3+
// Get returns the value if found, otherwise returns the zero value of the type
4+
func GetOrDefault[T comparable, V any](m map[T]V, key T, defaultValue V) V {
5+
value, ok := m[key]
6+
if !ok {
7+
return defaultValue
8+
}
9+
return value
10+
}
11+
312
// Keys returns a slice containing all the keys from the given map.
413
func Keys[T comparable, U any](m map[T]U) []T {
514
keys := make([]T, 0, len(m))

maps_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,61 @@ import (
77
"testing"
88
)
99

10+
func TestGetOrDefault(t *testing.T) {
11+
t.Parallel()
12+
13+
// Test cases
14+
testCases := []struct {
15+
name string
16+
inputMap map[string]int
17+
key string
18+
defaultValue int
19+
expected int
20+
}{
21+
{
22+
name: "existing key",
23+
inputMap: map[string]int{
24+
"foo": 42,
25+
"bar": 24,
26+
},
27+
key: "foo",
28+
defaultValue: 0,
29+
expected: 42,
30+
},
31+
{
32+
name: "non-existing key",
33+
inputMap: map[string]int{
34+
"foo": 42,
35+
"bar": 24,
36+
},
37+
key: "baz",
38+
defaultValue: 10,
39+
expected: 10,
40+
},
41+
{
42+
name: "zero default value",
43+
inputMap: map[string]int{
44+
"foo": 42,
45+
"bar": 24,
46+
},
47+
key: "baz",
48+
defaultValue: 0,
49+
expected: 0,
50+
},
51+
}
52+
53+
// Run test cases
54+
for _, testCase := range testCases {
55+
t.Run(testCase.name, func(t *testing.T) {
56+
result := GetOrDefault(testCase.inputMap, testCase.key, testCase.defaultValue)
57+
58+
if result != testCase.expected {
59+
t.Errorf("Test case '%s': expected %v but got %v", testCase.name, testCase.expected, result)
60+
}
61+
})
62+
}
63+
}
64+
1065
func TestKeys(t *testing.T) {
1166
t.Parallel()
1267

0 commit comments

Comments
 (0)