Skip to content

Commit c1bd073

Browse files
committed
added xslices.Map
1 parent 17331d3 commit c1bd073

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

internal/xslices/map.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package xslices
2+
3+
func Map[Key comparable, T any](x []T, key func(t T) Key) map[Key]T {
4+
m := make(map[Key]T, len(x))
5+
6+
for i := range x {
7+
m[key(x[i])] = x[i]
8+
}
9+
10+
return m
11+
}

internal/xslices/map_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package xslices
2+
3+
import (
4+
"github.com/stretchr/testify/require"
5+
"strconv"
6+
"testing"
7+
)
8+
9+
func TestMap(t *testing.T) {
10+
require.Equal(t,
11+
map[string]int{
12+
"1": 1,
13+
"2": 2,
14+
"3": 3,
15+
},
16+
Map([]int{1, 2, 3}, strconv.Itoa),
17+
)
18+
}

0 commit comments

Comments
 (0)