Last active
December 1, 2017 21:25
-
-
Save katherinebui/796eb446a6997b735892fb80e530d9fb to your computer and use it in GitHub Desktop.
My solution:
This file contains 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
require 'date' | |
class KeyValueStore | |
attr_accessor :record | |
def initialize() | |
@record = { | |
'Bob' => { | |
(DateTime.now - (100/1444.0)) => 'A', | |
(DateTime.now - (50/1444.0)) => 'B' | |
}, | |
'Sharon' => { | |
(DateTime.now - (50/1444.0)) => 'V', | |
(DateTime.now - (100/1444.0)) => 'O', | |
(DateTime.now - (19/1444.0)) => 'P', | |
(DateTime.now - (10/1444.0)) => 'K', | |
(DateTime.now - (100/1444.0)) => 'I' | |
} | |
} | |
# I initialized some sample data | |
end | |
def put(k,v) | |
if !@record[k] | |
@record[k] = {} | |
@record[k][DateTime.now] = v | |
else | |
@record[k][DateTime.now] = v | |
end | |
end | |
def get(k,timestamp) | |
# @record[k].keys == @record[k].keys.sort # this suggests that the keys are already sorted in the hash | |
# return @record[k].values[-1] if timestamp == nil # since the timestamp keys have already been sorted, I just pulled all the values (which comes back as an array), and returned the last value because we want the latest value if no timestamp is given | |
# but if we were to add key/value pairs and have the datetime not DateTime.now, I would have to give the timestamp a value for comparsion | |
if timestamp == nil | |
timestamp = DateTime.now | |
end | |
record_keys = @record[k].keys.sort! | |
result = '' | |
record_keys.each_with_index do |key, index| | |
if record_keys[index] < timestamp && record_keys[index+1] == nil || record_keys[index] < timestamp && timestamp < record_keys[index+1] | |
result = record_keys[index] | |
end | |
end | |
@record[k][result] ? @record[k][result] : nil | |
end | |
def peek | |
@record | |
end | |
end | |
store = KeyValueStore.new | |
store.put('Bob', 'C') | |
store.put('Bob', 'D') | |
store.peek | |
store.get('Bob', nil) | |
p store.get('Sharon', nil) | |
store.get('Sharon', DateTime.now) | |
store.get('Sharon', (DateTime.now - 15/1444.0)) | |
store.peek | |
# to see the output of the test code, just put the letter 'p' in front of it | |
# for example: 'p store.peek' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment