map.go (864B)
1 package slices 2 3 func Map[T any, R any](m []T, action func(T) R) (result []R) { 4 result = make([]R, len(m)) 5 for i, item := range m { 6 result[i] = action(item) 7 } 8 return 9 } 10 11 func MapWithError[T any, R any](m []T, action func(T) (R, error)) (result []R, err error) { 12 result = make([]R, len(m)) 13 for i, item := range m { 14 result[i], err = action(item) 15 if err != nil { 16 return nil, err 17 } 18 } 19 return 20 } 21 22 func FlatMap[T any, R any](m []T, action func(T) []R) (result []R) { 23 result = make([]R, 0, len(m)) 24 for _, item := range m { 25 result = append(result, action(item)...) 26 } 27 return 28 } 29 30 func FlatMapWithError[T any, R any](m []T, action func(T) ([]R, error)) (result []R, err error) { 31 result = make([]R, 0, len(m)) 32 for _, item := range m { 33 items, err := action(item) 34 if err != nil { 35 return nil, err 36 } 37 result = append(result, items...) 38 } 39 return 40 }