From e01570d9a17da6fb8b588385e80be3aa6e2b18d7 Mon Sep 17 00:00:00 2001 From: Mathieu Lemay <23462228+mathieu-lemay@users.noreply.github.com> Date: Fri, 1 Nov 2024 09:12:09 -0400 Subject: [PATCH] feat: Add RandomMapKey and RandomMapValuet (#182) These two functions are analog to RandomStringMapKey and RandomStringMapValue, in the same way RandomElement is to RandomStringElement. This was something I felt was missing as I was trying to get a random map element from a map than was not a map[string]string. Unlike their String counterpart though, no sorting is performed. Doing a sort would require the generics to be constrained to cmd.Ordered which I feel is too restrictive. Co-authored-by: Jonathan Schweder --- random_element.go | 20 ++++++++++++++++++++ random_element_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/random_element.go b/random_element.go index 0b33ebd..0e462ff 100644 --- a/random_element.go +++ b/random_element.go @@ -24,3 +24,23 @@ func RandomElementWeighted[T any](f Faker, elements map[int]T) T { return arrayOfElements[i] } + +func RandomMapKey[K comparable, V any](f Faker, m map[K]V) K { + keys := make([]K, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + + i := f.IntBetween(0, len(keys)-1) + return keys[i] +} + +func RandomMapValue[K comparable, V any](f Faker, m map[K]V) V { + values := make([]V, 0, len(m)) + for k := range m { + values = append(values, m[k]) + } + + i := f.IntBetween(0, len(values)-1) + return values[i] +} diff --git a/random_element_test.go b/random_element_test.go index c969fba..91e63cb 100644 --- a/random_element_test.go +++ b/random_element_test.go @@ -23,3 +23,27 @@ func TestRandomElementWeighted(t *testing.T) { Expect(t, true, got != "zeroChance") } } + +func TestRandomMapKey(t *testing.T) { + f := New() + m := map[int]string{ + 1: "one", + 5: "five", + 42: "forty two", + } + + randomInt := RandomMapKey(f, m) + Expect(t, true, randomInt == 1 || randomInt == 5 || randomInt == 42) +} + +func TestRandomMapValue(t *testing.T) { + f := New() + m := map[int]string{ + 1: "one", + 5: "five", + 42: "forty two", + } + + randomStr := RandomMapValue(f, m) + Expect(t, true, randomStr == "one" || randomStr == "five" || randomStr == "forty two") +}