aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--util.go13
-rw-r--r--util_test.go8
2 files changed, 21 insertions, 0 deletions
diff --git a/util.go b/util.go
index daf2817..ec2a3dd 100644
--- a/util.go
+++ b/util.go
@@ -11,6 +11,19 @@ func Must[T any](val T, err error) T {
return val
}
+// SliceMap applies a function to a slice and returns a new slice made
+// of the returned values.
+func SliceMap[T ~[]S, S, U any](f func(S) U, ts T) []U {
+ if len(ts) == 0 {
+ return nil
+ }
+ ret := make([]U, len(ts))
+ for i, t := range ts {
+ ret[i] = f(t)
+ }
+ return ret
+}
+
// NoCopy flags a type that embeds it as not to be copied. Go does not
// prevent values from being copied, but ‘go vet’ will pick it up and
// signal it, which can then be caught by many CI/CD pipelines.
diff --git a/util_test.go b/util_test.go
index 783c86b..a9b297e 100644
--- a/util_test.go
+++ b/util_test.go
@@ -21,3 +21,11 @@ func TestMust(s *testing.T) {
t.AssertNotPanics(func() { core.Must(42, nil) })
t.AssertEqual(42, core.Must(42, nil))
}
+
+func TestSliceMap(s *testing.T) {
+ t := core.T{T: s}
+
+ t.AssertEqual(([]int)(nil), core.SliceMap(func(int) int { return 0 }, ([]int)(nil)))
+ t.AssertEqual(([]int)(nil), core.SliceMap(func(int) int { return 0 }, []int{}))
+ t.AssertEqual([]int{42, 84}, core.SliceMap(func(x int) int { return x * 2 }, []int{21, 42}))
+}