Skip to content

Commit 2bfe01d

Browse files
authored
add slice convert + map convert (#2)
1 parent cf88ca6 commit 2bfe01d

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

map.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ func EachMap[K Comparable, V any](in map[K]V, call func(key K, value V)) {
1515
}
1616
}
1717

18+
func ConvertMap[K1, K2 comparable, V1, V2 any](in map[K1]V1, call func(key K1, value V1) (K2, V2)) (out map[K2]V2) {
19+
out = make(map[K2]V2, len(in))
20+
for k1, v1 := range in {
21+
k2, v2 := call(k1, v1)
22+
out[k2] = v2
23+
}
24+
return
25+
}
26+
1827
func FilterMap[K comparable, V any](in map[K]V, filter func(key K, value V) bool) (out map[K]V) {
1928
out = make(map[K]V, len(in))
2029
for k, v := range in {

slice.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ func Each[T any](in []T, call func(value T, index int)) {
1111
}
1212
}
1313

14+
func Convert[T, V any](in []T, call func(value T, index int) V) (out []V) {
15+
out = make([]V, len(in))
16+
for i, v := range in {
17+
out[i] = call(v, i)
18+
}
19+
return
20+
}
21+
1422
func Join[T any](in ...[]T) (out []T) {
1523
size := 0
1624
for _, m := range in {

0 commit comments

Comments
 (0)