github.com/leanovate/gopter@v0.2.9/gen/frequency.go (about) 1 package gen 2 3 import ( 4 "sort" 5 6 "github.com/leanovate/gopter" 7 ) 8 9 // Frequency combines multiple weighted generators of the the same result type 10 // The generators from weightedGens will be used accrding to the weight, i.e. generators 11 // with a hight weight will be used more often than generators with a low weight. 12 func Frequency(weightedGens map[int]gopter.Gen) gopter.Gen { 13 if len(weightedGens) == 0 { 14 return Fail(nil) 15 } 16 weights := make(sort.IntSlice, 0, len(weightedGens)) 17 max := 0 18 for weight := range weightedGens { 19 if weight > max { 20 max = weight 21 } 22 weights = append(weights, weight) 23 } 24 weights.Sort() 25 return func(genParams *gopter.GenParameters) *gopter.GenResult { 26 idx := weights.Search(genParams.Rng.Intn(max + 1)) 27 gen := weightedGens[weights[idx]] 28 29 result := gen(genParams) 30 result.Sieve = nil 31 return result 32 } 33 }