Sha256: 3dc51e2e593210bcee448269966cbcbb6ae87f5702bb05bd921be877d4281b1a

Contents?: true

Size: 1.05 KB

Versions: 6

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

module Prefab
  class WeightedValueResolver
    MAX_32_FLOAT = 4_294_967_294.0

    def initialize(weights, config_key, context_hash_value)
      @weights = weights
      @config_key = config_key
      @context_hash_value = context_hash_value
    end

    def resolve
      percent = @context_hash_value ? user_percent : rand

      index = variant_index(percent)

      @weights[index]
    end

    def user_percent
      to_hash = "#{@config_key}#{@context_hash_value}"
      int_value = Murmur3.murmur3_32(to_hash)
      int_value / MAX_32_FLOAT
    end

    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
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
prefab-cloud-ruby-0.24.5 lib/prefab/weighted_value_resolver.rb
prefab-cloud-ruby-0.24.4 lib/prefab/weighted_value_resolver.rb
prefab-cloud-ruby-0.24.3 lib/prefab/weighted_value_resolver.rb
prefab-cloud-ruby-0.24.2 lib/prefab/weighted_value_resolver.rb
prefab-cloud-ruby-0.24.1 lib/prefab/weighted_value_resolver.rb
prefab-cloud-ruby-0.24.0 lib/prefab/weighted_value_resolver.rb