# By Pseudon Mousie
class SlidingWindowMap
# Create a hash, with the keys as keys
# The values will be the timestamps when the key was used.
def initialize(keys, max_count, period_ms, verbose=false)
@verbose = verbose
@key_counts = Hash.new
keys.each{|key|
@key_counts[key] = []
}
@max_count = max_count
# store period in floating point seconds to match Time objects
@period_f_sec = period_ms / 1000.0
puts "keycounts:#{@key_counts.inspect}..." if @verbose
end
def getNextKey()
@key_counts.keys.each{|key|
puts "checking #{key}..." if @verbose
return key if has_uses_remaining?(key)
}
nil
end
# Calling this function counts as a "use"
# unless there are no uses available.
def has_uses_remaining?(key)
times_used = @key_counts[key]
# Clear out expired uses
while !(times_used.empty?) && (times_used.first < Time.now)
times_used.shift
end
if times_used.length < @max_count
times_used.push(Time.now + @period_f_sec)
return true
else
return false
end
end
end