Sha256: 16d61a5196a147e2758d6c96fedc73c5e534a4f86355b8a045661faafab689e2

Contents?: true

Size: 456 Bytes

Versions: 2

Compression:

Stored size: 456 Bytes

Contents

class WeightedList
  class Normalizer
    def self.call(collection)
      new(collection).call
    end

    def initialize(collection)
      @hash = collection.to_h
    end

    def call
      hash.each_with_object({}) do |(item, weight), normalized_hash|
        normalized_hash[item] = weight.fdiv(total_weight)
      end
    end

    private

    attr_reader :hash

    def total_weight
      @total_weight ||= hash.values.reduce(&:+)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
weighted_list-0.3.0 lib/weighted_list/normalizer.rb
weighted_list-0.2.0 lib/weighted_list/normalizer.rb