Created
September 22, 2016 18:16
-
-
Save saadbinakhlaq/643b5d6c9bd468e7e547a0236869d79d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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