Sha256: fa3887a1e50198b8ff67c6a62b0a50b29facdbc77d49846fd40fd78640b7ba6c

Contents?: true

Size: 844 Bytes

Versions: 1

Compression:

Stored size: 844 Bytes

Contents

# frozen_string_literal: true

require 'weighted_list/normalizer'
require 'weighted_list/version'
require 'weighted_list/sampler'

class WeightedList
  include Enumerable

  def initialize(collection)
    @hash = Normalizer.call(collection)
  end

  def each(&block)
    hash.keys.each(&block)
  end

  def sample(quantity = nil, random: Random)
    @random = random
    return single_item unless quantity
    (0...quantity).each_with_object(initial_memo) do |_index, memo|
      result = Sampler.new(memo[:current_list], random: random).call
      memo[:chosen].push(result.chosen)
      memo[:current_list] = result.remaining
    end[:chosen].compact
  end

  private

  attr_reader :hash, :random

  def initial_memo
    { chosen: [], current_list: hash }
  end

  def single_item
    Sampler.new(hash, random: random).call.chosen
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
weighted_list-0.2.0 lib/weighted_list.rb