diff --git a/helper/map.go b/helper/map.go index fc4330f..d54b198 100644 --- a/helper/map.go +++ b/helper/map.go @@ -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 }) }