Created
September 19, 2018 21:24
-
-
Save seanknox/aa79e627ebfb282360ad64a938adf665 to your computer and use it in GitHub Desktop.
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 'pry' | |
class Cache | |
attr_reader :value | |
attr_reader :version | |
attr_reader :versions | |
# we are storing values as Ruby hash values | |
def initialize(value = {}, version = 0, versions = []) | |
@value = value | |
@version = version | |
@versions = versions | |
end | |
def put(k, v) | |
# snapshot before we change any data | |
@versions << Cache.new(@value, @version) | |
# we assume new values are strings and convert to symbols, for easier get/setting. | |
new_value = {k.to_sym => v} | |
@value = @value.merge(new_value) | |
@version += 1 | |
puts "PUT(##{@version}) #{k} = #{v}" | |
end | |
def get(k, version = nil) | |
if !version.nil? && version < @versions.size - 1 | |
value = @versions[version].value | |
else | |
value = @value | |
end | |
if value[k.to_sym].nil? | |
puts "GET #{k} = <NULL>" | |
else | |
puts "GET #{k} = #{value[k.to_sym]}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment