Class: Prefab::WeightedValueResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/prefab/weighted_value_resolver.rb

Constant Summary collapse

MAX_32_FLOAT =
4_294_967_294.0

Instance Method Summary collapse

Constructor Details

#initialize(weights, config_key, lookup_key) ⇒ 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, lookup_key)
  @weights = weights
  @config_key = config_key
  @lookup_key = lookup_key
end

Instance Method Details

#resolveObject



13
14
15
16
17
18
19
# File 'lib/prefab/weighted_value_resolver.rb', line 13

def resolve
  percent = @lookup_key ? user_percent : rand

  index = variant_index(percent)

  @weights[index]
end

#user_percentObject



21
22
23
24
25
# File 'lib/prefab/weighted_value_resolver.rb', line 21

def user_percent
  to_hash = "#{@config_key}#{@lookup_key}"
  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