-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice_utils.go
More file actions
32 lines (25 loc) · 1008 Bytes
/
Copy pathslice_utils.go
File metadata and controls
32 lines (25 loc) · 1008 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package ezutil
// MapSlice applies a mapping function to each element of an input slice and returns a new slice.
// The function transforms elements of type T to type U using the provided mapperFunc.
// This is a generic utility for functional-style slice transformations.
func MapSlice[T any, U any](input []T, mapperFunc func(T) U) []U {
output := make([]U, len(input))
for i, v := range input {
output[i] = mapperFunc(v)
}
return output
}
// MapSliceWithError applies a mapping function to each element of an input slice with error handling.
// The function transforms elements of type T to type U using the provided mapperFunc.
// Returns an error immediately if any transformation fails, providing fail-fast behavior.
func MapSliceWithError[T any, U any](input []T, mapperFunc func(T) (U, error)) ([]U, error) {
output := make([]U, len(input))
for i, v := range input {
mapped, err := mapperFunc(v)
if err != nil {
return nil, err
}
output[i] = mapped
}
return output, nil
}