Skip to content

Instantly share code, notes, and snippets.

@calufa
Created November 20, 2023 16:03
Show Gist options
  • Save calufa/3999e6e2d9ff0c7347082bfeb0aab6ba to your computer and use it in GitHub Desktop.
Save calufa/3999e6e2d9ff0c7347082bfeb0aab6ba to your computer and use it in GitHub Desktop.
Exercise
# requirements
# in memory
# date and time as precise as possible
# return latest if time is in the future
# print('Hello')
# tests
# test with a time that is less than the time where the first document was added
# test if time is far in the future
# check if doc name doesnt exist
# edge cases
# if doc is bigger than the amount of memory available
# if docs are store at the same time
# notes
# check if keys are already sorted in python dict
import time
class DocumentStore:
documents = {}
def save(self, documentName, text):
if documentName not in self.documents:
self.documents[documentName] = {}
self.documents[documentName][time.time()] = text
def load(self, documentName):
if documentName not in self.documents:
return None
docs = self.documents[documentName]
return sorted(docs.items())[-1][1]
def loadFromTime(self, documentName, time):
if documentName not in self.documents:
return None
docs = self.documents[documentName]
sorted_docs = sorted(docs.items())
for i, _ in enumerate(sorted_docs):
print("--->", time, sorted_docs[i][0], i + 1, len(sorted_docs))
if time > sorted_docs[i][0] and i + 1 == len(sorted_docs):
return sorted_docs[i][1]
if time > sorted_docs[i][0] and time < sorted_docs[i + 1][0]:
return sorted_docs[i][1]
elif time < sorted_docs[i][0]:
return None
store = DocumentStore()
store.save("test-doc", "text-test")
store.save("test-doc", "text-test 2")
store.save("test-doc-1", "abc")
store.save("", "abc - 2")
from_time = time.time()
time.sleep(1)
store.save("test-doc", "text-test 3")
latest_doc = store.load("test-doc")
print(latest_doc)
doc_from_time = store.loadFromTime("test-doc", from_time)
print(doc_from_time)
doc_from_time = store.loadFromTime("test-doc", from_time + 1000000)
print(doc_from_time)
doc_from_time = store.loadFromTime("", from_time + 1000000)
print(doc_from_time)
doc_from_time = store.loadFromTime("xyz", from_time + 1000000)
print(doc_from_time)
doc_from_time = store.load("xyz")
print(doc_from_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment