Skip to content

Commit

Permalink
add the generic function to convert a slice to map
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Mar 26, 2024
1 parent a3be9bf commit a27a0a7
Showing 1 changed file with 18 additions and 20 deletions.
38 changes: 18 additions & 20 deletions helper/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,38 +50,36 @@ func MapValuesFunc[M ~map[K]V, T any, K comparable, V any](maps M, convert func(
return values
}

func ToMapWithIndex[S ~[]E, K comparable, V, E any](s S, convert func(int, E) (K, V)) map[K]V {
_len := len(s)
maps := make(map[K]V, _len)
for i := 0; i < _len; i++ {
k, v := convert(i, s[i])
maps[k] = v
}
return maps
}

func ToMap[S ~[]E, K comparable, V, E any](s S, convert func(E) (K, V)) map[K]V {
return ToMapWithIndex(s, func(_ int, e E) (K, V) { return convert(e) })
}

// ToSetMap converts a slice s to a set map.
func ToSetMap[S ~[]T, T comparable](s S) map[T]struct{} {
m := make(map[T]struct{}, len(s))
for _, k := range s {
m[k] = struct{}{}
}
return m
return ToMap(s, func(e T) (T, struct{}) { return e, struct{}{} })
}

// ToBoolMap converts a slice s to a bool map.
func ToBoolMap[S ~[]T, T comparable](s S) map[T]bool {
m := make(map[T]bool, len(s))
for _, k := range s {
m[k] = true
}
return m
return ToMap(s, func(e T) (T, bool) { return e, true })
}

// ToSetMapFunc converts a slice s to a set map by a conversion function.
func ToSetMapFunc[S ~[]T, K comparable, T any](s S, convert func(T) K) map[K]struct{} {
m := make(map[K]struct{}, len(s))
for _, k := range s {
m[convert(k)] = struct{}{}
}
return m
return ToMap(s, func(e T) (K, struct{}) { return convert(e), struct{}{} })
}

// ToBoolMapFunc converts a slice s to a bool map by a conversion function.
func ToBoolMapFunc[S ~[]T, K comparable, T any](s S, convert func(T) K) map[K]bool {
m := make(map[K]bool, len(s))
for _, k := range s {
m[convert(k)] = true
}
return m
return ToMap(s, func(e T) (K, bool) { return convert(e), true })
}

0 comments on commit a27a0a7

Please sign in to comment.