Class: Periodical::Filter::Period

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

Overview

Keep count sorted objects per period.

Direct Known Subclasses

Daily, Hourly, Monthly, Quarterly, Weekly, Yearly

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

Instance Method Summary collapse

Constructor Details

#initialize(count) ⇒ Period

Returns a new instance of Period.

Parameters:

  • count

    the number of items we should retain.



39
40
41
# File 'lib/periodical/filter.rb', line 39

def initialize(count)
	@count = count
end

Instance Attribute Details

#countObject (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

Parameters:

  • order

    can be a key in ORDER or a lambda.

  • block

    is applied to the value and should typically return a Time instance.



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

Raises:

  • (NotImplementedError)


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