Skip to content

Instantly share code, notes, and snippets.

@saadbinakhlaq
Created September 22, 2016 18:16
Show Gist options
  • Save saadbinakhlaq/643b5d6c9bd468e7e547a0236869d79d to your computer and use it in GitHub Desktop.
Save saadbinakhlaq/643b5d6c9bd468e7e547a0236869d79d to your computer and use it in GitHub Desktop.
Dir[File.dirname(__FILE__) + '/application/*.rb'].each { |file| require file }
class KV
attr_reader :hash
def initialize
@hash = Hash.new { |h, k| h[k] = {} }
end
def set(key, value)
@hash[key][Time.now.to_i] = value
end
def get(key, timestamp = nil)
if timestamp.nil?
@hash[key][latest_key(key)]
else
@hash[key][fuzzy_match_timestamp(key, timestamp)]
end
end
private
def latest_key(key)
@hash[key].keys.sort.last
end
def fuzzy_match_timestamp(key, timestamp)
timestamp_values = @hash[key].keys.map { |key| timestamp - key }.select { |values| values >= 0 }
timestamp - timestamp_values.min
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment