Class: OccurenceCounter

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

Overview

This OccurenceCounter class can be used to count the occurence of entries. Optionally the number of different entries that are tracked can be limited. In case the limit is reached, the oldest entered or incremented entry will be dropped for each new entry.

Instance Method Summary collapse

Constructor Details

#initialize(size = 0) ⇒ OccurenceCounter

Optionally you can limit the number of different tracked entries.



19
20
21
22
# File 'lib/OccurenceCounter.rb', line 19

def initialize(size = 0)
  @max = size
  @buffer = []
end

Instance Method Details

#delete(entry) ⇒ Object



54
55
56
# File 'lib/OccurenceCounter.rb', line 54

def delete(entry)
  @buffer.delete(entry)
end

#eachObject

This is the iterator to read out the list of entries with their counters. Each call of yield retrieves an entry-counter pair.



60
61
62
# File 'lib/OccurenceCounter.rb', line 60

def each
  @buffer.each { |entry, count| yield(entry, count) }
end

#push(entry) ⇒ Object

This is the main function to track entries. Whenever it’s called, the function tries to lookup the entry in the buffer. In case it already in there, the counter is increased. New entries are inserted with a count of 1.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/OccurenceCounter.rb', line 28

def push(entry)
  return if entry == nil

  for i in 0 ... @buffer.length
    if @buffer[i][0] == entry
      if i == 0
        # If the new entry is the same as the last one, we just
        # increase the counter.
        @buffer[0] = [entry, @buffer[0][1]]
        return
      end
      # Move entry to buffer position 0 and shift down all entries
      # between position 0 and i - 1
      count = @buffer[i][1]
      i.downto(1) { |j| @buffer[j] = @buffer[j - 1] }
       @buffer[0] = [entry, count + 1]
      return
    end
  end
  # Insert new entry at front and drop the last one if the buffer
  # became too big.
  @buffer.insert(0, [entry, 1])
  @buffer.pop if @max > 0 && @buffer.length > @max
  return
end