Skip to content

Commit

Permalink
add Index function
Browse files Browse the repository at this point in the history
  • Loading branch information
ixiongjianbo committed Jun 8, 2023
1 parent e5ed3a6 commit bf1b7a8
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ type KeyTypeDef interface {
string | int8 | int | int32 | int64 | float32 | float64
}

// MakeMap usage: m1 := MakeMap[int](userSlice, `age`)
// MakeMap slice convert map
// appMaps := array.MakeMap[int64](apps, `plan_id`)
// appMaps result: map[plan_id]app
func MakeMap[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string) map[KeyType]ItemType {
result := make(map[KeyType]ItemType)
for _, elem := range slice {
Expand Down Expand Up @@ -190,6 +192,10 @@ func MakeMap[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string) m
return result
}

// MakeMaps slice convert map
// Example :
// appMaps := array.MakeMaps[int64](apps, `plan_id`)
// appMaps result: map[plan_id][]apps
func MakeMaps[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string) map[KeyType][]ItemType {
result := make(map[KeyType][]ItemType)
for _, elem := range slice {
Expand Down Expand Up @@ -221,3 +227,28 @@ func MakeMaps[KeyType KeyTypeDef, ItemType any](slice []ItemType, field string)
}
return result
}

// Index get slice elem
// Example:
//
// a := []func(){
// func() {
// fmt.Println(123)
// },
// func() {
// fmt.Println(456)
// },
// }
// ss := Index(a, 2)
// if ss != nil {
// ss()
// } else {
// fmt.Println(`ss is nil`)
// }
func Index[T any](list []T, index int) T {
var result = new(T)
if len(list) <= index || index < 0 {
return *result
}
return list[index]
}

0 comments on commit bf1b7a8

Please sign in to comment.