Skip to content

Commit

Permalink
feat: Add RandomMapKey and RandomMapValuet
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mathieu-lemay committed Oct 31, 2024
1 parent 62c2c94 commit 017255b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
20 changes: 20 additions & 0 deletions random_element.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}
24 changes: 24 additions & 0 deletions random_element_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

0 comments on commit 017255b

Please sign in to comment.