Class: Pickup::MappedList

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(list, func, opts = nil) ⇒ MappedList

Returns a new instance of MappedList.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/pickup.rb', line 80

def initialize(list, func, opts=nil)
  if Hash === opts
    @key_func = opts[:key_func]
    @weight_func = opts[:weight_func] || weight_func
    @uniq = opts[:uniq] || false
  else
    if !!opts == opts
      # If opts is explicitly provided as a boolean, show the deprecated warning.
      warn "[DEPRECATED] Passing uniq as a boolean to MappedList's initialize method is deprecated. Please use the opts hash instead."
    end

    @uniq = opts || false
  end

  @func = func
  @list = list
  @current_state = 0
end

Instance Attribute Details

#funcObject (readonly)

Returns the value of attribute func.



78
79
80
# File 'lib/pickup.rb', line 78

def func
  @func
end

#key_funcObject (readonly)

Returns the value of attribute key_func.



78
79
80
# File 'lib/pickup.rb', line 78

def key_func
  @key_func
end

#listObject (readonly)

Returns the value of attribute list.



78
79
80
# File 'lib/pickup.rb', line 78

def list
  @list
end

#uniqObject (readonly)

Returns the value of attribute uniq.



78
79
80
# File 'lib/pickup.rb', line 78

def uniq
  @uniq
end

#weight_funcObject (readonly)

Returns the value of attribute weight_func.



78
79
80
# File 'lib/pickup.rb', line 78

def weight_func
  @weight_func
end

Instance Method Details

#each(&blk) ⇒ Object



107
108
109
110
111
112
113
114
115
# File 'lib/pickup.rb', line 107

def each(&blk)
  CircleIterator.new(@list, func, max, key_func: @key_func, weight_func: weight_func).each do |item|
    if uniq
      true if yield item
    else
      nil while yield(item)
    end
  end
end

#get_random_items(nums) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/pickup.rb', line 123

def get_random_items(nums)
  current_num = nums.shift
  items = []
  each do |item, counter, mx|
    break unless current_num
    if counter%(mx+1) > current_num%mx
      items << item
      current_num = nums.shift
      true
    end
  end
  items
end

#maxObject



137
138
139
140
141
142
143
# File 'lib/pickup.rb', line 137

def max
  @max ||= begin
    max = 0
    list.each{ |item| max += func.call(weight_func.call(item)) }
    max
  end
end

#random(count) ⇒ Object



117
118
119
120
121
# File 'lib/pickup.rb', line 117

def random(count)
  raise "List is shorter then count of items you want to get" if uniq && list.size < count
  nums = count.times.map{ rand(max) }.sort
  get_random_items(nums)
end