Skip to content

Commit 9a66fc6

Browse files
committed
add map to slice
1 parent bf89fca commit 9a66fc6

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

map.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,11 @@ func ReduceMap[K Comparable, V any](in map[K]V, call func(result, value V, key K
9494
}
9595
return
9696
}
97+
98+
func ToSlice[K Comparable, V any, T any](in map[K]V, call func(value V, key K) T) (out []T) {
99+
out = make([]T, 0, len(in))
100+
for _, k := range Keys[K, V](in) {
101+
out = append(out, call(in[k], k))
102+
}
103+
return
104+
}

map_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,21 @@ func TestUnit_ReduceMap(t *testing.T) {
6868
})
6969
casecheck.Equal(t, "010203", out)
7070
}
71+
72+
func TestUnit_ToSlice(t *testing.T) {
73+
type A struct {
74+
K int
75+
V string
76+
}
77+
out := do.ToSlice[int, string, A](map[int]string{2: "02", 1: "01", 3: "03"}, func(value string, key int) A {
78+
return A{
79+
K: key,
80+
V: value,
81+
}
82+
})
83+
casecheck.Equal(t, []A{
84+
{K: 1, V: "01"},
85+
{K: 2, V: "02"},
86+
{K: 3, V: "03"},
87+
}, out)
88+
}

0 commit comments

Comments
 (0)