class TimeTrap
TimeTrap
is a data structure that allows stores instances of keys added over time. At its core, TimeTrap
is a hash where keys are data instances tracked and values are arrays of time(s) when teh data instance occurred.
Public Class Methods
# File lib/timetrap.rb, line 9 def initialize @tt = {} end
Public Instance Methods
Add an instance of value to timetrap. time defaults to seconds since epoch unless you provide a value.
# File lib/timetrap.rb, line 15 def add(value, time=Time.now.to_i) @tt[value] ||= Deque.new return @tt[value].push(time) end
@return count of distinct keys which have been added
# File lib/timetrap.rb, line 75 def count return @tt.count end
allows block code to be run on each entry in TimeTrap
# File lib/timetrap.rb, line 33 def each(&block) @tt.each(&block) end
@param [Object] value key to retrieve. @return [Hash] key = value, value = array of time entries. nil if missing
# File lib/timetrap.rb, line 22 def get(value) ret = @tt[value].nil? ? nil : {value => @tt[value].queue} return ret end
@param [Object] key key to look up in TimeTrap
@return [bool] obvious??
# File lib/timetrap.rb, line 70 def has_key?(key) return @tt.has_key?(key) end
@return [Array] array of values that have been added
# File lib/timetrap.rb, line 28 def keys return @tt.keys end
@param [Fixnum] secs number of seconds before current time for window @return [Hash] returns hash of values in window key=added data, value = count of occurences in last argued secondswindow
# File lib/timetrap.rb, line 63 def last(secs) t = Time.now.to_i return window(t - secs, t) end
allows direct set access to internal hash @param [Object] key value being tracked
# File lib/timetrap.rb, line 91 def set(key, value) @tt[key] = value end
@return [Array] of values sorted by argued block code
# File lib/timetrap.rb, line 44 def sort_by(&block) @tt.sort_by(&block) end
@param [Fixnum] number of entries to return @return [TimeTrap] TimeTrap
consting of top values
# File lib/timetrap.rb, line 50 def top(rank) ret = TimeTrap.new @tt.sort_by {|k,v| -v.count}.map{|k,v| ret.set(k, v) rank -= 1 break if rank <= 0 } return ret end
@param [FixNum] start_sec beginning on time frame @param [FixNum] end_sec end of time frame @return [Hash] key = value added to TimeTrap
, value = count of instances in the window
# File lib/timetrap.rb, line 82 def window(start_sec, end_sec) ret = TimeTrap.new @tt.each {|k,v| ret.set(k, v.window(start_sec, end_sec)) if v.window(start_sec, end_sec).count > 0} return ret end