Class: Prefab::WeightedValueResolver
- Inherits:
-
Object
- Object
- Prefab::WeightedValueResolver
- Defined in:
- lib/prefab/weighted_value_resolver.rb
Constant Summary collapse
- MAX_32_FLOAT =
4_294_967_294.0
Instance Method Summary collapse
-
#initialize(weights, config_key, context_hash_value) ⇒ WeightedValueResolver
constructor
A new instance of WeightedValueResolver.
- #resolve ⇒ Object
- #user_percent ⇒ Object
- #variant_index(percent_through_distribution) ⇒ Object
Constructor Details
#initialize(weights, config_key, context_hash_value) ⇒ WeightedValueResolver
Returns a new instance of WeightedValueResolver.
7 8 9 10 11 |
# File 'lib/prefab/weighted_value_resolver.rb', line 7 def initialize(weights, config_key, context_hash_value) @weights = weights @config_key = config_key @context_hash_value = context_hash_value end |
Instance Method Details
#resolve ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/prefab/weighted_value_resolver.rb', line 13 def resolve percent = @context_hash_value ? user_percent : rand index = variant_index(percent) [@weights[index], index] end |
#user_percent ⇒ Object
21 22 23 24 25 |
# File 'lib/prefab/weighted_value_resolver.rb', line 21 def user_percent to_hash = "#{@config_key}#{@context_hash_value}" int_value = Murmur3.murmur3_32(to_hash) int_value / MAX_32_FLOAT end |
#variant_index(percent_through_distribution) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/prefab/weighted_value_resolver.rb', line 27 def variant_index(percent_through_distribution) distribution_space = @weights.inject(0) { |sum, v| sum + v.weight } bucket = distribution_space * percent_through_distribution sum = 0 @weights.each_with_index do |variant_weight, index| return index if bucket < sum + variant_weight.weight sum += variant_weight.weight end # In the event that all weights are zero, return the last variant @weights.size - 1 end |