Class: Histograffle::Histogram

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(d = [{}, {}]) ⇒ Histogram

Returns a new instance of Histogram.



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

def initialize(d=[{}, {}])
  @data   = d[0].dup
  @lookup = d[1].dup
  @data.default = 0
end

Class Method Details

.from_mongo(v) ⇒ Object



93
94
95
96
97
# File 'lib/histograffle.rb', line 93

def self.from_mongo(v)
  # puts "from_mongo:  " + v.inspect
  return v if v.nil? || v.is_a?(self)
  v ? self.new([v[0], intify_keys(v[1])]) : nil
end

.to_mongo(v) ⇒ Object



86
87
88
89
90
91
# File 'lib/histograffle.rb', line 86

def self.to_mongo(v)
  # puts "to_mongo:  " + v.inspect
  return v if v.nil?
  return Array.to_mongo(v) if v.is_a?(Array)
  [v.data, stringify_keys(v.lookup)]
end

Instance Method Details

#<<(other) ⇒ Object



76
77
78
79
# File 'lib/histograffle.rb', line 76

def <<(other)
  other.data.each{|k,v| eat(k,v) }
  self
end

#==(other) ⇒ Object



81
82
83
84
# File 'lib/histograffle.rb', line 81

def ==(other)
  return false unless other.is_a?(self.class)
  [@data, @lookup] == [other.data, other.lookup]
end

#[](n) ⇒ Object



40
41
42
# File 'lib/histograffle.rb', line 40

def [](n)
  @lookup[n]
end

#dataObject



6
7
8
# File 'lib/histograffle.rb', line 6

def data
  @data.dup
end

#distributionObject



44
45
46
# File 'lib/histograffle.rb', line 44

def distribution
  ladder.reverse
end

#eat(o, n = 1) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/histograffle.rb', line 24

def eat( o, n=1 )
  if o.is_a? self.class
    self << o
  else
    o = [o] unless o.respond_to? :each
    o.each do |t|
      @data[t] += n
      @lookup[@data[t]] ||= []
      @lookup[@data[t]] << t
      @lookup[@data[t]-n].delete(t) if @lookup[@data[t]-n]
      @lookup.delete(@data[t]-n) if (@lookup[@data[t]-n] || []).empty?
    end
  end
  self
end

#flat_top(n) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/histograffle.rb', line 64

def flat_top( n )
  result = []
  ladder.reverse.each do |count|
    @lookup[count].each do |word|
      result << word
      return result if (n -= 1) < 1
    end
  end
  result

end

#ladderObject



48
49
50
# File 'lib/histograffle.rb', line 48

def ladder
  @lookup.keys.sort
end

#lookupObject



10
11
12
13
14
15
16
# File 'lib/histograffle.rb', line 10

def lookup
  lu = @lookup.dup
  lu.each_key do |k|
    lu[k] = lu[k].dup
  end
  lu
end

#top(n) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/histograffle.rb', line 52

def top( n )
  result = {}
  distribution.each do |count|
    @lookup[count].each do |word|
      result[count] ||= []
      result[count] << word
      return result if (n -= 1) < 1
    end
  end
  result
end