Class: PercentualDistributor

Inherits:
Object
  • Object
show all
Defined in:
lib/ektoplayer/views/trackrenderer.rb

Instance Method Summary collapse

Constructor Details

#initialize(total: 0, parts: []) ⇒ PercentualDistributor

Returns a new instance of PercentualDistributor.



4
5
6
7
# File 'lib/ektoplayer/views/trackrenderer.rb', line 4

def initialize(total: 0, parts: [])
   @total, @parts = total, parts
   @results = nil
end

Instance Method Details

#add_part(n) ⇒ Object



14
15
16
17
# File 'lib/ektoplayer/views/trackrenderer.rb', line 14

def add_part(n)
   @parts << n
   @results = nil
end

#get_for(part) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ektoplayer/views/trackrenderer.rb', line 19

def get_for(part)
   fail ArgumentError unless @parts.include? part

   unless @results
      @results = Hash.new { |h,k| h[k] = [] }

      part_total, results_total = @parts.sum, 0
      @parts.each_with_index do |p,i|
         v = @total * p / part_total
         @results[p] << v
         results_total += v
      end

      @results.each do |k, values|
         values.map! do |v|
            if results_total > @total
               results_total -= 1
               v - 1
            elsif results_total < @total
               results_total += 1
               v + 1
            else
               v
            end
         end
      end
   end

   @results[part].unshift(r = @results[part].pop)
   r
end

#increment_total(n) ⇒ Object



9
10
11
12
# File 'lib/ektoplayer/views/trackrenderer.rb', line 9

def increment_total(n)
   @total += n
   @results = nil
end