Skip to content

Commit

Permalink
add xmap.Values (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajatprabha authored Aug 21, 2023
1 parent 45bb106 commit 6b68cd9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
13 changes: 13 additions & 0 deletions generic/xmap/values.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package xmap

// Values returns a new slice with all values from the given input map.
// Note: Returned values slice is not sorted.
func Values[M ~map[K]V, K comparable, V any](input M) []V {
output := make([]V, 0, len(input))

for _, v := range input {
output = append(output, v)
}

return output
}
42 changes: 42 additions & 0 deletions generic/xmap/values_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package xmap

import (
"sort"
"testing"

"github.com/stretchr/testify/assert"
)

func TestIntValues(t *testing.T) {
vals := Values(map[string]int{
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
})

sort.Ints(vals)
assert.EqualValues(t, []int{1, 2, 3, 4, 5, 6}, vals)
}

func TestStructValues(t *testing.T) {
type testStruct struct {
ID int
Valid bool
}

vals := Values(map[string]testStruct{
"1": {ID: 1, Valid: true},
"2": {ID: 2},
"3": {ID: 3, Valid: true},
"4": {ID: 4},
})

sort.Slice(vals, func(i, j int) bool {
return vals[i].ID < vals[j].ID
})

assert.EqualValues(t, []testStruct{{ID: 1, Valid: true}, {ID: 2}, {ID: 3, Valid: true}, {ID: 4}}, vals)
}

0 comments on commit 6b68cd9

Please sign in to comment.