Skip to content

Instantly share code, notes, and snippets.

@saadbinakhlaq saadbinakhlaq/kv.rb
Created Sep 22, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.