From 85427c4ee5bdc7529dbb75b9832586a303981996 Mon Sep 17 00:00:00 2001 From: alexfilus Date: Thu, 15 Aug 2024 16:20:48 +0200 Subject: [PATCH] do not create wait groups for slices with len less than 2 --- parallel/slice.go | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/parallel/slice.go b/parallel/slice.go index a70fb70f..9db70537 100644 --- a/parallel/slice.go +++ b/parallel/slice.go @@ -5,6 +5,14 @@ import "sync" // Map manipulates a slice and transforms it to a slice of another type. // `iteratee` is call in parallel. Result keep the same order. func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { + if len(collection) == 0 { + return []R{} + } + + if len(collection) == 1 { + return []R{iteratee(collection[0], 0)} + } + result := make([]R, len(collection)) var wg sync.WaitGroup @@ -28,6 +36,15 @@ func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { // ForEach iterates over elements of collection and invokes iteratee for each element. // `iteratee` is call in parallel. func ForEach[T any](collection []T, iteratee func(item T, index int)) { + if len(collection) == 0 { + return + } + + if len(collection) == 1 { + iteratee(collection[0], 0) + return + } + var wg sync.WaitGroup wg.Add(len(collection)) @@ -45,6 +62,14 @@ func ForEach[T any](collection []T, iteratee func(item T, index int)) { // The iteratee is invoked with index as argument. // `iteratee` is call in parallel. func Times[T any](count int, iteratee func(index int) T) []T { + if count == 0 { + return []T{} + } + + if count == 1 { + return []T{iteratee(0)} + } + result := make([]T, count) var wg sync.WaitGroup @@ -70,6 +95,16 @@ func Times[T any](count int, iteratee func(index int) T) []T { func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) map[U]Slice { result := map[U]Slice{} + if len(collection) == 0 { + return result + } + + if len(collection) == 1 { + key := iteratee(collection[0]) + result[key] = collection + return result + } + var mu sync.Mutex var wg sync.WaitGroup wg.Add(len(collection)) @@ -97,7 +132,15 @@ func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(it // of running each element of collection through iteratee. // `iteratee` is call in parallel. func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice { - result := []Slice{} + if len(collection) == 0 { + return []Slice{} + } + + if len(collection) == 1 { + return []Slice{collection} + } + + result := make([]Slice, 0, 1) seen := map[K]int{} var mu sync.Mutex