From 8ff6a647fa110e96f995e22c2a5da6ef74d4befc Mon Sep 17 00:00:00 2001 From: Nathan Baulch Date: Fri, 16 Aug 2024 07:46:37 +1000 Subject: [PATCH] Tidy up --- CHANGELOG.md | 2 +- README.md | 22 ++++++++++++---------- channel.go | 4 ++-- condition_example_test.go | 16 ++++++++-------- errors_example_test.go | 4 ++-- errors_test.go | 26 +++++++++++++------------- find.go | 2 +- intersect.go | 2 +- map_example_test.go | 2 -- math.go | 10 +++++----- parallel/slice.go | 2 +- retry.go | 22 +++++++++++----------- retry_example_test.go | 2 +- retry_test.go | 4 ++-- slice.go | 6 +++--- slice_example_test.go | 2 ++ slice_test.go | 6 +++--- string.go | 4 ++-- type_manipulation.go | 2 +- type_manipulation_test.go | 2 +- 20 files changed, 72 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b9e4e11..18e63f68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,7 @@ Improvement: - lo.Associate / lo.SliceToMap: faster memory allocation Chore: -- Remove *_test.go files from releases, in order to cleanup dev dependencies +- Remove *_test.go files from releases, in order to clean up dev dependencies ## 1.36.0 (2022-11-28) diff --git a/README.md b/README.md index 836e608b..6d4ca604 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ Supported helpers for tuples: Supported helpers for time and duration: - [Duration](#duration) -- [Duration0 -> Duration10](#duration0-duration10) +- [Duration0 -> Duration10](#duration0---duration10) Supported helpers for channels: @@ -1990,7 +1990,7 @@ ok := lo.Every([]int{0, 1, 2, 3, 4, 5}, []int{0, 6}) ### EveryBy -Returns true if the predicate returns true for all of the elements in the collection or if the collection is empty. +Returns true if the predicate returns true for all elements in the collection or if the collection is empty. ```go b := EveryBy([]int{1, 2, 3, 4}, func(x int) bool { @@ -2913,7 +2913,9 @@ f(42, -4) ### Attempt -Invokes a function N times until it returns valid output. Returning either the caught error or nil. When first argument is less than `1`, the function runs until a successful response is returned. +Invokes a function N times until it returns valid output. Returns either the caught error or nil. + +When the first argument is less than `1`, the function runs until a successful response is returned. ```go iter, err := lo.Attempt(42, func(i int) error { @@ -2953,9 +2955,9 @@ For more advanced retry strategies (delay, exponential backoff...), please take ### AttemptWithDelay -Invokes a function N times until it returns valid output, with a pause between each call. Returning either the caught error or nil. +Invokes a function N times until it returns valid output, with a pause between each call. Returns either the caught error or nil. -When first argument is less than `1`, the function runs until a successful response is returned. +When the first argument is less than `1`, the function runs until a successful response is returned. ```go iter, duration, err := lo.AttemptWithDelay(5, 2*time.Second, func(i int, duration time.Duration) error { @@ -2976,9 +2978,9 @@ For more advanced retry strategies (delay, exponential backoff...), please take ### AttemptWhile -Invokes a function N times until it returns valid output. Returning either the caught error or nil, and along with a bool value to identifying whether it needs invoke function continuously. It will terminate the invoke immediately if second bool value is returned with falsy value. +Invokes a function N times until it returns valid output. Returns either the caught error or nil, along with a bool value to determine whether the function should be invoked again. It will terminate the invoke immediately if the second return value is false. -When first argument is less than `1`, the function runs until a successful response is returned. +When the first argument is less than `1`, the function runs until a successful response is returned. ```go count1, err1 := lo.AttemptWhile(5, func(i int) (error, bool) { @@ -3001,9 +3003,9 @@ For more advanced retry strategies (delay, exponential backoff...), please take ### AttemptWhileWithDelay -Invokes a function N times until it returns valid output, with a pause between each call. Returning either the caught error or nil, and along with a bool value to identifying whether it needs to invoke function continuously. It will terminate the invoke immediately if second bool value is returned with falsy value. +Invokes a function N times until it returns valid output, with a pause between each call. Returns either the caught error or nil, along with a bool value to determine whether the function should be invoked again. It will terminate the invoke immediately if the second return value is false. -When first argument is less than `1`, the function runs until a successful response is returned. +When the first argument is less than `1`, the function runs until a successful response is returned. ```go count1, time1, err1 := lo.AttemptWhileWithDelay(5, time.Millisecond, func(i int, d time.Duration) (error, bool) { @@ -3492,7 +3494,7 @@ if rateLimitErr, ok := lo.ErrorsAs[*RateLimitError](err); ok { We executed a simple benchmark with a dead-simple `lo.Map` loop: -See the full implementation [here](./benchmark_test.go). +See the full implementation [here](./map_benchmark_test.go). ```go _ = lo.Map[int64](arr, func(x int64, i int) string { diff --git a/channel.go b/channel.go index 228705ae..8458bf9d 100644 --- a/channel.go +++ b/channel.go @@ -99,7 +99,7 @@ func DispatchingStrategyRandom[T any](msg T, index uint64, channels []<-chan T) // DispatchingStrategyWeightedRandom distributes messages in a weighted manner. // If the channel capacity is exceeded, another random channel will be selected and so on. func DispatchingStrategyWeightedRandom[T any](weights []int) DispatchingStrategy[T] { - seq := []int{} + var seq []int for i := 0; i < len(weights); i++ { for j := 0; j < weights[i]; j++ { @@ -169,7 +169,7 @@ func SliceToChannel[T any](bufferSize int, collection []T) <-chan T { // ChannelToSlice returns a slice built from channels items. Blocks until channel closes. func ChannelToSlice[T any](ch <-chan T) []T { - collection := []T{} + var collection []T for item := range ch { collection = append(collection, item) diff --git a/condition_example_test.go b/condition_example_test.go index 1700967e..340095d6 100644 --- a/condition_example_test.go +++ b/condition_example_test.go @@ -98,7 +98,7 @@ func ExampleIfF() { // 3 } -func ExampleifElse_ElseIf() { +func Example_ifElse_ElseIf() { result1 := If(true, 1). ElseIf(false, 2). Else(3) @@ -138,7 +138,7 @@ func ExampleifElse_ElseIf() { // 3 } -func ExampleifElse_ElseIfF() { +func Example_ifElse_ElseIfF() { result1 := If(true, 1). ElseIf(false, 2). Else(3) @@ -178,7 +178,7 @@ func ExampleifElse_ElseIfF() { // 3 } -func ExampleifElse_Else() { +func Example_ifElse_Else() { result1 := If(true, 1). ElseIf(false, 2). Else(3) @@ -218,7 +218,7 @@ func ExampleifElse_Else() { // 3 } -func ExampleifElse_ElseF() { +func Example_ifElse_ElseF() { result1 := If(true, 1). ElseIf(false, 2). Else(3) @@ -304,7 +304,7 @@ func ExampleSwitch() { // 3 } -func ExampleswitchCase_Case() { +func Example_switchCase_Case() { result1 := Switch[int, string](1). Case(1, "1"). Case(2, "2"). @@ -350,7 +350,7 @@ func ExampleswitchCase_Case() { // 3 } -func ExampleswitchCase_CaseF() { +func Example_switchCase_CaseF() { result1 := Switch[int, string](1). Case(1, "1"). Case(2, "2"). @@ -396,7 +396,7 @@ func ExampleswitchCase_CaseF() { // 3 } -func ExampleswitchCase_Default() { +func Example_switchCase_Default() { result1 := Switch[int, string](1). Case(1, "1"). Case(2, "2"). @@ -442,7 +442,7 @@ func ExampleswitchCase_Default() { // 3 } -func ExampleswitchCase_DefaultF() { +func Example_switchCase_DefaultF() { result1 := Switch[int, string](1). Case(1, "1"). Case(2, "2"). diff --git a/errors_example_test.go b/errors_example_test.go index 1594a0c2..88006bd6 100644 --- a/errors_example_test.go +++ b/errors_example_test.go @@ -363,6 +363,7 @@ func ExampleTryOr5() { fmt.Printf("%v %v %v %v %v %v\n", value1, value2, value3, value4, value5, ok3) // Output: 21 hello false {bar} 4.2 false } + func ExampleTryOr6() { value1, value2, value3, value4, value5, value6, ok3 := TryOr6(func() (int, string, bool, foo, float64, string, error) { panic("my error") @@ -405,8 +406,7 @@ func ExampleTryCatchWithErrorValue() { // Output: catch: trigger an error } -type myError struct { -} +type myError struct{} func (e myError) Error() string { return "my error" diff --git a/errors_test.go b/errors_test.go index 08cace9d..11743a1f 100644 --- a/errors_test.go +++ b/errors_test.go @@ -53,7 +53,7 @@ func TestMust(t *testing.T) { is.PanicsWithValue("operation should fail: assert.AnError general error for testing", func() { Must0(cb(), "operation should fail") }) - + is.PanicsWithValue("must: invalid err type 'int', should either be a bool or an error", func() { Must0(0) }) @@ -271,11 +271,11 @@ func TestTry(t *testing.T) { func TestTryX(t *testing.T) { t.Parallel() is := assert.New(t) - + is.True(Try1(func() error { return nil })) - + is.True(Try2(func() (string, error) { return "", nil })) @@ -295,11 +295,11 @@ func TestTryX(t *testing.T) { is.True(Try6(func() (string, string, string, string, string, error) { return "", "", "", "", "", nil })) - + is.False(Try1(func() error { panic("error") })) - + is.False(Try2(func() (string, error) { panic("error") })) @@ -319,11 +319,11 @@ func TestTryX(t *testing.T) { is.False(Try6(func() (string, string, string, string, string, error) { panic("error") })) - + is.False(Try1(func() error { return errors.New("foo") })) - + is.False(Try2(func() (string, error) { return "", errors.New("foo") })) @@ -513,13 +513,13 @@ func TestTryWithErrorValue(t *testing.T) { }) is.False(ok) is.Equal("error", err) - + err, ok = TryWithErrorValue(func() error { return errors.New("foo") }) is.False(ok) is.EqualError(err.(error), "foo") - + err, ok = TryWithErrorValue(func() error { return nil }) @@ -535,7 +535,7 @@ func TestTryCatch(t *testing.T) { TryCatch(func() error { panic("error") }, func() { - //error was caught + // error was caught caught = true }) is.True(caught) @@ -544,7 +544,7 @@ func TestTryCatch(t *testing.T) { TryCatch(func() error { return nil }, func() { - //no error to be caught + // no error to be caught caught = true }) is.False(caught) @@ -558,7 +558,7 @@ func TestTryCatchWithErrorValue(t *testing.T) { TryCatchWithErrorValue(func() error { panic("error") }, func(val any) { - //error was caught + // error was caught caught = val == "error" }) is.True(caught) @@ -567,7 +567,7 @@ func TestTryCatchWithErrorValue(t *testing.T) { TryCatchWithErrorValue(func() error { return nil }, func(val any) { - //no error to be caught + // no error to be caught caught = true }) is.False(caught) diff --git a/find.go b/find.go index ea577ae2..59c23460 100644 --- a/find.go +++ b/find.go @@ -441,7 +441,7 @@ func Last[T any](collection []T) (T, bool) { return collection[length-1], true } -// Returns the last element of a collection or zero value if empty. +// LastOrEmpty returns the last element of a collection or zero value if empty. func LastOrEmpty[T any](collection []T) T { i, _ := Last(collection) return i diff --git a/intersect.go b/intersect.go index 2df0e741..b2cf0727 100644 --- a/intersect.go +++ b/intersect.go @@ -33,7 +33,7 @@ func Every[T comparable](collection []T, subset []T) bool { return true } -// EveryBy returns true if the predicate returns true for all of the elements in the collection or if the collection is empty. +// EveryBy returns true if the predicate returns true for all elements in the collection or if the collection is empty. func EveryBy[T any](collection []T, predicate func(item T) bool) bool { for i := range collection { if !predicate(collection[i]) { diff --git a/map_example_test.go b/map_example_test.go index 8edc7fe0..e9347a04 100644 --- a/map_example_test.go +++ b/map_example_test.go @@ -15,7 +15,6 @@ func ExampleKeys() { sort.Strings(result) fmt.Printf("%v", result) // Output: [bar baz foo] - } func ExampleUniqKeys() { @@ -26,7 +25,6 @@ func ExampleUniqKeys() { sort.Strings(result) fmt.Printf("%v", result) // Output: [bar foo] - } func ExampleValues() { diff --git a/math.go b/math.go index e866f88e..cae7624e 100644 --- a/math.go +++ b/math.go @@ -32,7 +32,7 @@ func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum in // step set to zero will return empty array. // Play: https://go.dev/play/p/0r6VimXAi9H func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) []T { - result := []T{} + var result []T if start == end || step == 0 { return result } @@ -87,20 +87,20 @@ func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Comple // Mean calculates the mean of a collection of numbers. func Mean[T constraints.Float | constraints.Integer](collection []T) T { - var length T = T(len(collection)) + var length = T(len(collection)) if length == 0 { return 0 } - var sum T = Sum(collection) + var sum = Sum(collection) return sum / length } // MeanBy calculates the mean of a collection of numbers using the given return value from the iteration function. func MeanBy[T any, R constraints.Float | constraints.Integer](collection []T, iteratee func(item T) R) R { - var length R = R(len(collection)) + var length = R(len(collection)) if length == 0 { return 0 } - var sum R = SumBy(collection, iteratee) + var sum = SumBy(collection, iteratee) return sum / length } diff --git a/parallel/slice.go b/parallel/slice.go index a70fb70f..647b81e5 100644 --- a/parallel/slice.go +++ b/parallel/slice.go @@ -97,7 +97,7 @@ 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{} + var result []Slice seen := map[K]int{} var mu sync.Mutex diff --git a/retry.go b/retry.go index f026aa33..82e8f82f 100644 --- a/retry.go +++ b/retry.go @@ -104,7 +104,6 @@ func (d *debounceBy[T]) reset(key T) { for i := range d.callbacks { d.callbacks[i](key, count) } - }) } @@ -141,7 +140,8 @@ func NewDebounceBy[T comparable](duration time.Duration, f ...func(key T, count }, d.cancel } -// Attempt invokes a function N times until it returns valid output. Returning either the caught error or nil. When first argument is less than `1`, the function runs until a successful response is returned. +// Attempt invokes a function N times until it returns valid output. Returns either the caught error or nil. +// When the first argument is less than `1`, the function runs until a successful response is returned. // Play: https://go.dev/play/p/3ggJZ2ZKcMj func Attempt(maxIteration int, f func(index int) error) (int, error) { var err error @@ -158,8 +158,8 @@ func Attempt(maxIteration int, f func(index int) error) (int, error) { } // AttemptWithDelay invokes a function N times until it returns valid output, -// with a pause between each call. Returning either the caught error or nil. -// When first argument is less than `1`, the function runs until a successful +// with a pause between each call. Returns either the caught error or nil. +// When the first argument is less than `1`, the function runs until a successful // response is returned. // Play: https://go.dev/play/p/tVs6CygC7m1 func AttemptWithDelay(maxIteration int, delay time.Duration, f func(index int, duration time.Duration) error) (int, time.Duration, error) { @@ -182,9 +182,9 @@ func AttemptWithDelay(maxIteration int, delay time.Duration, f func(index int, d } // AttemptWhile invokes a function N times until it returns valid output. -// Returning either the caught error or nil, and along with a bool value to identify -// whether it needs invoke function continuously. It will terminate the invoke -// immediately if second bool value is returned with falsy value. When first +// Returns either the caught error or nil, along with a bool value to determine +// whether the function should be invoked again. It will terminate the invoke +// immediately if the second return value is false. When the first // argument is less than `1`, the function runs until a successful response is // returned. func AttemptWhile(maxIteration int, f func(int) (error, bool)) (int, error) { @@ -206,10 +206,10 @@ func AttemptWhile(maxIteration int, f func(int) (error, bool)) (int, error) { } // AttemptWhileWithDelay invokes a function N times until it returns valid output, -// with a pause between each call. Returning either the caught error or nil, and along -// with a bool value to identify whether it needs to invoke function continuously. -// It will terminate the invoke immediately if second bool value is returned with falsy -// value. When first argument is less than `1`, the function runs until a successful +// with a pause between each call. Returns either the caught error or nil, along +// with a bool value to determine whether the function should be invoked again. +// It will terminate the invoke immediately if the second return value is false. +// When the first argument is less than `1`, the function runs until a successful // response is returned. func AttemptWhileWithDelay(maxIteration int, delay time.Duration, f func(int, time.Duration) (error, bool)) (int, time.Duration, error) { var err error diff --git a/retry_example_test.go b/retry_example_test.go index 3560c2f0..68bcdf1e 100644 --- a/retry_example_test.go +++ b/retry_example_test.go @@ -12,7 +12,7 @@ import ( func ExampleNewDebounce() { i := int32(0) - calls := []int32{} + var calls []int32 mu := sync.Mutex{} debounce, cancel := NewDebounce(time.Millisecond, func() { diff --git a/retry_test.go b/retry_test.go index 1ac00703..f4094a76 100644 --- a/retry_test.go +++ b/retry_test.go @@ -82,7 +82,7 @@ func TestAttemptWithDelay(t *testing.T) { }) is.Equal(iter1, 1) - is.Greater(dur1, 0*time.Millisecond) + is.GreaterOrEqual(dur1, 0*time.Millisecond) is.Less(dur1, 1*time.Millisecond) is.Equal(err1, nil) is.Equal(iter2, 6) @@ -187,7 +187,7 @@ func TestAttemptWhileWithDelay(t *testing.T) { }) is.Equal(iter1, 1) - is.Greater(dur1, 0*time.Millisecond) + is.GreaterOrEqual(dur1, 0*time.Millisecond) is.Less(dur1, 1*time.Millisecond) is.Nil(err1) diff --git a/slice.go b/slice.go index d2d3fd84..3166c8c8 100644 --- a/slice.go +++ b/slice.go @@ -40,7 +40,7 @@ func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { // // Play: https://go.dev/play/p/-AuYXfy7opz func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { - result := []R{} + var result []R for i := range collection { if r, ok := callback(collection[i], i); ok { @@ -204,7 +204,7 @@ func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { // of running each element of collection through iteratee. // Play: https://go.dev/play/p/NfQ_nGjkgXW func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice { - result := []Slice{} + var result []Slice seen := map[K]int{} for i := range collection { @@ -480,7 +480,7 @@ func Reject[T any, Slice ~[]T](collection Slice, predicate func(item T, index in // - the result of the mapping operation and // - whether the result element should be included or not. func RejectMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { - result := []R{} + var result []R for i := range collection { if r, ok := callback(collection[i], i); !ok { diff --git a/slice_example_test.go b/slice_example_test.go index 0d64d8f0..f6b1b65b 100644 --- a/slice_example_test.go +++ b/slice_example_test.go @@ -88,6 +88,7 @@ func ExampleForEach() { // 3 // 4 } + func ExampleForEachWhile() { list := []int64{1, 2, -math.MaxInt, 4} @@ -103,6 +104,7 @@ func ExampleForEachWhile() { // 1 // 2 } + func ExampleTimes() { result := Times(3, func(i int) string { return strconv.FormatInt(int64(i), 10) diff --git a/slice_test.go b/slice_test.go index abb9450e..b0ca6af4 100644 --- a/slice_test.go +++ b/slice_test.go @@ -144,8 +144,8 @@ func TestForEach(t *testing.T) { // check of callback is called for every element and in proper order - callParams1 := []string{} - callParams2 := []int{} + var callParams1 []string + var callParams2 []int ForEach([]string{"a", "b", "c"}, func(item string, i int) { callParams1 = append(callParams1, item) @@ -1006,7 +1006,7 @@ func TestSplice(t *testing.T) { is.Equal([]string{"a", "b", "c", "d", "e", "f", "g"}, sample) is.Equal(results, []string{"1", "2", "a", "b", "c", "d", "e", "f", "g"}) - // backard + // backward results = Splice(sample, -2, "1", "2") is.Equal([]string{"a", "b", "c", "d", "e", "f", "g"}, sample) is.Equal(results, []string{"a", "b", "c", "d", "e", "1", "2", "f", "g"}) diff --git a/string.go b/string.go index f6aae7be..94dddde4 100644 --- a/string.go +++ b/string.go @@ -85,7 +85,7 @@ func ChunkString[T ~string](str T, size int) []T { return []T{str} } - var chunks []T = make([]T, 0, ((len(str)-1)/size)+1) + var chunks = make([]T, 0, ((len(str)-1)/size)+1) currentLen := 0 currentStart := 0 for i := range str { @@ -181,7 +181,7 @@ func Ellipsis(str string, length int) string { return str } -// Elipse trims truncates a string to a specified length and appends an ellipsis if truncated. +// Elipse trims and truncates a string to a specified length and appends an ellipsis if truncated. // // Deprecated: Use Ellipsis instead. func Elipse(str string, length int) string { diff --git a/type_manipulation.go b/type_manipulation.go index ef070281..448abe96 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -69,7 +69,7 @@ func FromSlicePtr[T any](collection []*T) []T { }) } -// FromSlicePtr returns a slice with the pointer values or the fallback value. +// FromSlicePtrOr returns a slice with the pointer values or the fallback value. func FromSlicePtrOr[T any](collection []*T, fallback T) []T { return Map(collection, func(x *T, _ int) T { if x == nil { diff --git a/type_manipulation_test.go b/type_manipulation_test.go index 3a63013d..4c8575e9 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -146,7 +146,7 @@ func TestToAnySlice(t *testing.T) { is := assert.New(t) in1 := []int{0, 1, 2, 3} - in2 := []int{} + var in2 []int out1 := ToAnySlice(in1) out2 := ToAnySlice(in2)