Skip to content

Instantly share code, notes, and snippets.

@marshall-lee
Last active October 1, 2019 12:14
Show Gist options
  • Save marshall-lee/e77b5d3218b7584f0e68cdadb00531a3 to your computer and use it in GitHub Desktop.
Save marshall-lee/e77b5d3218b7584f0e68cdadb00531a3 to your computer and use it in GitHub Desktop.
require 'singleton'
class AtMost
include Singleton
def initialize
@table = Hash.new { |h, k| h[k] = -1 }
end
def call(n)
key = caller(1, 2)
yield if (@table[key] = (@table[key] + 1) % n).zero?
end
def self.call(n)
instance.call(n) { yield }
end
end
class Throttle
include Singleton
def initialize
@table = Hash.new { |h, k| h[k] = Time.at(0) }
end
def call(delay)
key = caller(1, 2)
was = @table[key]
now = Time.now
if now - was >= delay
@table[key] = now
yield
end
end
def self.call(n)
instance.call(n) { yield }
end
end
require 'logger'
logger = Logger.new($stdout)
logger.info "Testing AtMost"
1000.times do # should print "foo" 10 times and "bar" 10 times
AtMost.call(100) { logger.info "foo" }
AtMost.call(100) { logger.info "bar" }
end
logger.info "Testing Throttle"
30.times do # should print "foo" ~ 3 times
Throttle.call(1) { logger.info "foo" }
sleep(0.1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment