diff --git a/generic/xmap/values.go b/generic/xmap/values.go new file mode 100644 index 0000000..b61581c --- /dev/null +++ b/generic/xmap/values.go @@ -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 +} diff --git a/generic/xmap/values_test.go b/generic/xmap/values_test.go new file mode 100644 index 0000000..e265b92 --- /dev/null +++ b/generic/xmap/values_test.go @@ -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) +}