diff --git a/src/cmd/test/main.go b/src/cmd/test/main.go index a5e3fbf..3055a0c 100644 --- a/src/cmd/test/main.go +++ b/src/cmd/test/main.go @@ -2,9 +2,15 @@ package main import ( "github.com/surdeus/godat/src/mapx" + "github.com/surdeus/godat/src/slicex" "fmt" ) +type Struct struct { + Name string + Value int +} + func main() { m := map[string] string { "Key1" : "Value1", @@ -16,7 +22,19 @@ func main() { 2 : "Val2", 7 : "Val7", } + s := []Struct { + {"Name1", 1}, + {"Name2", 2}, + } + fmt.Println(m) + fmt.Println(slicex.MakeMap( + s, + func(v Struct) string { + return v.Name + }, + )) + fmt.Printf("%q\n", mapx.Keys(m)) fmt.Printf("%q\n", mapx.Values(m)) fmt.Printf("%q\n", mapx.Reverse(m)) diff --git a/src/slicex/main.go b/src/slicex/main.go new file mode 100644 index 0000000..0e4f457 --- /dev/null +++ b/src/slicex/main.go @@ -0,0 +1,16 @@ +package slicex + +func MakeMap[K comparable, V any]( + values []V, + fn func(V) (K), +) map[K] V { + var k K + + r := make(map[K] V) + for _, v := range values { + k = fn(v) + r[k] = v + } + + return r +}