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") +}