Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Mar 20, 2023
1 parent fd5561a commit f3826f7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 19 deletions.
17 changes: 9 additions & 8 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ func Values[K comparable, V any](in map[K]V) []V {
return result
}

// ValueOr returns the value of the given key or the fallback value if the key is not present.
// Play: https://go.dev/play/p/bAq9mHErB4V
func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V {
if v, ok := in[key]; ok {
return v
}
return fallback
}

// PickBy returns same map type filtered by given predicate.
// Play: https://go.dev/play/p/kdg8GR_QMmf
func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool) map[K]V {
Expand Down Expand Up @@ -96,14 +105,6 @@ func OmitByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V {
return r
}

// ValueOr returns the value of the given key or the fallback value if the key is not present.
func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V {
if v, ok := in[key]; ok {
return v
}
return fallback
}

// Entries transforms a map into array of key/value pairs.
// Play:
func Entries[K comparable, V any](in map[K]V) []Entry[K, V] {
Expand Down
10 changes: 10 additions & 0 deletions map_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ func ExampleValues() {
// Output: [1 2]
}

func ExampleValueOr() {
kv := map[string]int{"foo": 1, "bar": 2}

result1 := ValueOr(kv, "foo", 42)
result2 := ValueOr(kv, "baz", 42)

fmt.Printf("%v %v", result1, result2)
// Output: 1 42
}

func ExamplePickBy() {
kv := map[string]int{"foo": 1, "bar": 2, "baz": 3}

Expand Down
22 changes: 11 additions & 11 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ func TestValues(t *testing.T) {
is.Equal(r1, []int{1, 2})
}

func TestValueOr(t *testing.T) {
t.Parallel()
is := assert.New(t)

r1 := ValueOr(map[string]int{"foo": 1}, "bar", 2)
is.Equal(r1, 2)

r2 := ValueOr(map[string]int{"foo": 1}, "foo", 2)
is.Equal(r2, 1)
}

func TestPickBy(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down Expand Up @@ -87,17 +98,6 @@ func TestOmitByValues(t *testing.T) {
is.Equal(r1, map[string]int{"bar": 2})
}

func TestValueOr(t *testing.T) {
t.Parallel()
is := assert.New(t)

r1 := ValueOr(map[string]int{"foo": 1}, "bar", 2)
is.Equal(r1, 2)

r2 := ValueOr(map[string]int{"foo": 1}, "foo", 2)
is.Equal(r2, 1)
}

func TestEntries(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down

0 comments on commit f3826f7

Please sign in to comment.