Created
June 7, 2019 03:08
-
-
Save compwron/e58c5e8fffb455a520506d636f772949 to your computer and use it in GitHub Desktop.
bad cache
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
thing1 = { data: 'data1', size: 10 } | |
thing2 = { data: 'data2', size: 20 } | |
thing3 = { data: 'data3', size: 5 } | |
require 'time' | |
require 'ap' | |
class Cache | |
def initialize(size:) | |
@size = size | |
@things = [] | |
@locations = {} # key: @things pointer | |
@cache_utilization = 0 | |
end | |
def put(key, thing) | |
if @locations[key] | |
to_drop = @locations[key] | |
@cache_utilization -= to_drop[:size] | |
@locations.delete(to_drop[:key]) | |
@things.delete_at(@things.find_index { |data| data[:key] == key }) # :( | |
end | |
while @cache_utilization + thing[:size] > @size | |
dropped_thing = @things.shift | |
@cache_utilization -= dropped_thing[:size] | |
@locations.delete(dropped_thing[:key]) | |
end | |
@locations[key] = thing | |
@things << thing.merge(key: key) | |
@cache_utilization += thing[:size] | |
end | |
def get(key) | |
value = @locations[key] | |
return unless value | |
idx = @things.find_index { |data| data[:key] == key } | |
@things.delete_at(idx) # :( | |
@things << value | |
end | |
end | |
c = Cache.new(size: 30) | |
c.put(:a, thing1) | |
# ap c.inspect | |
c.put(:a, { data: 'hi', size: 9 }) | |
p c.inspect | |
c.put(:b, thing2) | |
p c.get(:a) | |
p c.inspect | |
c.put(:c, thing3) # out of space, thing 1 is dropped | |
p c.inspect | |
# p c.get(:a) | |
# p c.get(:b) | |
# p c.get(:c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment