-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
45bb106
commit 6b68cd9
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |