From e567155eb1b41eac66ceff2fba7a253ceb624075 Mon Sep 17 00:00:00 2001 From: Aykhan Shahsuvarov Date: Thu, 29 May 2025 22:10:41 +0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20Refactor=20'RandomValueCycle'=20?= =?UTF-8?q?and=20'getKeyValueGeneratorFunc'=20functions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requests/request.go | 12 ++++-------- utils/slice.go | 36 ++++++++++++++++++++++-------------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/requests/request.go b/requests/request.go index 5cb810a..8624655 100644 --- a/requests/request.go +++ b/requests/request.go @@ -203,19 +203,15 @@ func getKeyValueGeneratorFunc[ isRandom := false for _, kv := range keyValueSlice { - valuesLen := len(kv.Value) - - getValueFunc := func() string { return "" } - if valuesLen == 1 { - getValueFunc = func() string { return kv.Value[0] } - } else if valuesLen > 1 { - getValueFunc = utils.RandomValueCycle(kv.Value, localRand) + if valuesLen := len(kv.Value); valuesLen > 1 { isRandom = true } getKeyValueSlice = append( getKeyValueSlice, - map[string]func() string{kv.Key: getValueFunc}, + map[string]func() string{ + kv.Key: utils.RandomValueCycle(kv.Value, localRand), + }, ) } diff --git a/utils/slice.go b/utils/slice.go index 34f955a..b3d5f4e 100644 --- a/utils/slice.go +++ b/utils/slice.go @@ -18,24 +18,32 @@ func Flatten[T any](nested [][]*T) []*T { // have been returned at least once. After all values have been returned, the function will // reset and start cycling through the values in a random order again. // The returned function isn't thread-safe and should be used in a single-threaded context. -func RandomValueCycle[Value any](values []Value, localRand *rand.Rand) func() Value { +func RandomValueCycle[T any](values []T, localRand *rand.Rand) func() T { var ( - clientsCount = len(values) - currentIndex = localRand.Intn(clientsCount) + valuesLen = len(values) + currentIndex = localRand.Intn(valuesLen) stopIndex = currentIndex ) - return func() Value { - client := values[currentIndex] - currentIndex++ - if currentIndex == clientsCount { - currentIndex = 0 - } - if currentIndex == stopIndex { - currentIndex = localRand.Intn(clientsCount) - stopIndex = currentIndex - } + switch valuesLen { + case 0: + var zero T + return func() T { return zero } + case 1: + return func() T { return values[0] } + default: + return func() T { + value := values[currentIndex] + currentIndex++ + if currentIndex == valuesLen { + currentIndex = 0 + } + if currentIndex == stopIndex { + currentIndex = localRand.Intn(valuesLen) + stopIndex = currentIndex + } - return client + return value + } } }