Skip to content

Commit

Permalink
Add utils.MapKeys and utils.MapValues (#19)
Browse files Browse the repository at this point in the history
* Add utils.MapKeys and utils.MapValues

* Update map_values.go
  • Loading branch information
aidenwallis authored Nov 26, 2022
1 parent 5cc8072 commit b30be7b
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 0 deletions.
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])
}
}

0 comments on commit b30be7b

Please sign in to comment.