Sha256: 5dbf5a985fe54ad341e6621a06ecfede19e9ef49a454252621f84de0fe626184
Contents?: true
Size: 1.01 KB
Versions: 11
Compression:
Stored size: 1.01 KB
Contents
# frozen_string_literal: true module Prefab class WeightedValueResolver MAX_32_FLOAT = 4_294_967_294.0 def initialize(weights, config_key, lookup_key) @weights = weights @config_key = config_key @lookup_key = lookup_key end def resolve percent = @lookup_key ? user_percent : rand index = variant_index(percent) @weights[index] end def user_percent to_hash = "#{@config_key}#{@lookup_key}" 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
11 entries across 11 versions & 1 rubygems