1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 16:22:26 +08:00

feat: add GetOrSet

This commit is contained in:
dudaodong
2024-06-24 17:28:51 +08:00
parent aeef0418a4
commit a220220f09
5 changed files with 122 additions and 0 deletions

View File

@@ -436,3 +436,15 @@ func ToSortedSlicesWithComparator[K comparable, V any](m map[K]V, comparator fun
return keys, sortedValues
}
// GetOrSet returns value of the given key or set the given value value if not present
// Play: todo
func GetOrSet[K comparable, V any](m map[K]V, key K, value V) V {
if v, ok := m[key]; ok {
return v
}
m[key] = value
return value
}

View File

@@ -524,3 +524,19 @@ func ExampleToSortedSlicesWithComparator() {
// [3 2 1]
// [c b a]
}
func ExampleGetOrSet() {
m := map[int]string{
1: "a",
}
result1 := GetOrSet(m, 1, "1")
result2 := GetOrSet(m, 2, "b")
fmt.Println(result1)
fmt.Println(result2)
// Output:
// a
// b
}

View File

@@ -691,3 +691,19 @@ func TestToSortedSlicesWithComparator(t *testing.T) {
})
}
}
func TestGetOrSet(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestGetOrSet")
m := map[int]string{
1: "a",
}
result1 := GetOrSet(m, 1, "1")
result2 := GetOrSet(m, 2, "b")
assert.Equal("a", result1)
assert.Equal("b", result2)
}