Skip to content

Commit

Permalink
add: random element and weighted random element.
Browse files Browse the repository at this point in the history
  • Loading branch information
arshamalh committed Apr 18, 2024
1 parent 7c7a782 commit e0bc79b
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
7 changes: 7 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,13 @@ func TestMap(t *testing.T) {
Expect(t, true, len(mp) > 0)
}

func TestRandomStringElement(t *testing.T) {
f := New()
m := []string{"str1", "str2"}
randomStr := f.RandomStringElement(m)
Expect(t, true, randomStr == "str1" || randomStr == "str2")
}

func TestRandomStringMapKey(t *testing.T) {
f := New()
m := map[string]string{"k0": "v0", "k1": "v1"}
Expand Down
26 changes: 26 additions & 0 deletions random_element.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package faker

// RandomElement returns a fake random element from a given list of elements
func RandomElement[T any](f Faker, elements ...T) T {
i := f.IntBetween(0, len(elements)-1)
return elements[i]
}

// RandomElementWeighted takes faker instance and a list of elements in the form of map[weight]element,
// it then selects one of the elements randomly and returns it,
//
// Elements with higher weight have more chance to be returned.
func RandomElementWeighted[T any](f Faker, elements map[int]T) T {
arrayOfElements := make([]T, 0)

for weight, value := range elements {
// TODO: there is an accepted proposal for generic slices.Repeat function in Go 1.23
for i := 0; i < weight; i++ {
arrayOfElements = append(arrayOfElements, value)
}
}

i := f.IntBetween(0, len(arrayOfElements)-1)

return arrayOfElements[i]
}
25 changes: 25 additions & 0 deletions random_element_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package faker

import "testing"

func TestRandomElement(t *testing.T) {
f := New()
m := []string{"str1", "str2"}
randomStr := RandomElement(f, m...)
Expect(t, true, randomStr == "str1" || randomStr == "str2")
}

func TestRandomElementWeighted(t *testing.T) {
f := New()
m := map[int]string{
0: "zeroChance",
1: "someChance",
5: "moreChance",
}

for i := 0; i < 5; i++ {
got := RandomElementWeighted(f, m)
Expect(t, true, got == "someChance" || got == "moreChance")
Expect(t, true, got != "zeroChance")
}
}

0 comments on commit e0bc79b

Please sign in to comment.