Class: Periodical::Filter::Period
- Inherits:
-
Object
- Object
- Periodical::Filter::Period
- Defined in:
- lib/periodical/filter.rb
Overview
Keep count sorted objects per period.
Constant Summary collapse
- ORDER =
Given times a and b, should we prefer a?
{ # We want `a` if `a` < `b`, i.e. it's older. old: ->(a, b){a < b}, # We want `a` if `a` > `b`, i.e. it's newer. new: ->(a, b){a > b} }
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
Instance Method Summary collapse
- #filter(values, keep: :old, &block) ⇒ Object
-
#initialize(count) ⇒ Period
constructor
A new instance of Period.
- #key(t) ⇒ Object
- #mktime(year, month = 1, day = 1, hour = 0, minute = 0, second = 0) ⇒ Object
Constructor Details
#initialize(count) ⇒ Period
Returns a new instance of Period.
39 40 41 |
# File 'lib/periodical/filter.rb', line 39 def initialize(count) @count = count end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
77 78 79 |
# File 'lib/periodical/filter.rb', line 77 def count @count end |
Instance Method Details
#filter(values, keep: :old, &block) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/periodical/filter.rb', line 45 def filter(values, keep: :old, &block) slots = {} keep = ORDER.fetch(keep, keep) values.each do |value| time = block_given? ? yield(value) : value granular_key = key(time) # We filter out this value if the slot is already full and we prefer the existing value. if existing_value = slots[granular_key] existing_time = block_given? ? yield(existing_value) : existing_value next if keep.call(existing_time, time) end slots[granular_key] = value end sorted_values = slots.values.sort return sorted_values.first(@count) end |
#key(t) ⇒ Object
69 70 71 |
# File 'lib/periodical/filter.rb', line 69 def key(t) raise NotImplementedError end |
#mktime(year, month = 1, day = 1, hour = 0, minute = 0, second = 0) ⇒ Object
73 74 75 |
# File 'lib/periodical/filter.rb', line 73 def mktime(year, month=1, day=1, hour=0, minute=0, second=0) return Time.new(year, month, day, hour, minute, second) end |