Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utils.MapKeys and utils.MapValues #19

Merged
merged 2 commits into from
Nov 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions utils/map_keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package utils

// MapKeys returns all keys in a given map, **the order will not be stable, you should sort these values if needed.**
func MapKeys[K comparable, V any](v map[K]V) []K {
resp := make([]K, 0, len(v))
for k := range v {
resp = append(resp, k)
}
return resp
}
30 changes: 30 additions & 0 deletions utils/map_keys_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package utils_test

import (
"sort"
"testing"

"github.com/aidenwallis/go-utils/internal/assert"
"github.com/aidenwallis/go-utils/utils"
)

func TestMapKeys(t *testing.T) {
t.Parallel()

out := []int{1, 2, 3}
in := map[int]struct{}{
1: {},
2: {},
3: {},
}

v := utils.MapKeys(in)
sort.SliceStable(v, func(i, j int) bool {
return v[i] < v[j]
})

assert.Equal(t, 3, len(v))
for i := range out {
assert.Equal(t, out[i], v[i])
}
}
10 changes: 10 additions & 0 deletions utils/map_values.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package utils

// MapValues returns all values in a given map, **the order is not stable, you should sort it if you need a stable order.**
func MapValues[K comparable, V any](in map[K]V) []V {
out := make([]V, 0, len(in))
for _, v := range in {
out = append(out, v)
}
return out
}
30 changes: 30 additions & 0 deletions utils/map_values_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package utils_test

import (
"sort"
"testing"

"github.com/aidenwallis/go-utils/internal/assert"
"github.com/aidenwallis/go-utils/utils"
)

func TestMapValues(t *testing.T) {
t.Parallel()

out := []int{1, 2, 3}
in := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}

v := utils.MapValues(in)
sort.SliceStable(v, func(i, j int) bool {
return v[i] < v[j]
})

assert.Equal(t, 3, len(v))
for i := range out {
assert.Equal(t, out[i], v[i])
}
}