Added slicex package.
This commit is contained in:
parent
0a277876bb
commit
df52a9102d
2 changed files with 34 additions and 0 deletions
|
@ -2,9 +2,15 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/surdeus/godat/src/mapx"
|
"github.com/surdeus/godat/src/mapx"
|
||||||
|
"github.com/surdeus/godat/src/slicex"
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type Struct struct {
|
||||||
|
Name string
|
||||||
|
Value int
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
m := map[string] string {
|
m := map[string] string {
|
||||||
"Key1" : "Value1",
|
"Key1" : "Value1",
|
||||||
|
@ -16,7 +22,19 @@ func main() {
|
||||||
2 : "Val2",
|
2 : "Val2",
|
||||||
7 : "Val7",
|
7 : "Val7",
|
||||||
}
|
}
|
||||||
|
s := []Struct {
|
||||||
|
{"Name1", 1},
|
||||||
|
{"Name2", 2},
|
||||||
|
}
|
||||||
|
|
||||||
fmt.Println(m)
|
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.Keys(m))
|
||||||
fmt.Printf("%q\n", mapx.Values(m))
|
fmt.Printf("%q\n", mapx.Values(m))
|
||||||
fmt.Printf("%q\n", mapx.Reverse(m))
|
fmt.Printf("%q\n", mapx.Reverse(m))
|
||||||
|
|
16
src/slicex/main.go
Normal file
16
src/slicex/main.go
Normal file
|
@ -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
|
||||||
|
}
|
Loading…
Reference in a new issue