Created
March 23, 2012 10:24
-
-
Save michel/2169339 to your computer and use it in GitHub Desktop.
LRU caching code kata
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
class Cache | |
attr_accessor :max_size | |
def initialize | |
@max_size = 99 | |
@cache = {} | |
end | |
def store(key,object) | |
@cache[key] = [0,object] | |
purge_old | |
key | |
end | |
def fetch(key) | |
@cache[key][1] if @cache[key] | |
end | |
private | |
def purge_old | |
update_keys | |
delete_oldest if @max_size < @cache.size | |
end | |
def update_keys | |
@cache.each { |k,v| @cache[k][0] +=1 } | |
end | |
def delete_oldest | |
oldest = @cache.values.map { |v| v[0]}.max | |
@cache.reject! { |k,v| v[0] ==oldest} | |
end | |
describe Cache do | |
let(:cache) { Cache.new} | |
let(:object) { "object" } | |
let(:object2) { "object2"} | |
let(:object3) { "object3"} | |
let(:object4) { "object4"} | |
it "stores an object item using a key" do | |
cache.store(:key,object) | |
cache.fetch(:key).should eql(object) | |
end | |
it "stores multiple objects by keys" do | |
cache.store(:key,object) | |
cache.store(:key2,object2) | |
cache.fetch(:key2).should eql(object2) | |
end | |
it "removes the oldest cached object when the maximum cache is reached" do | |
cache.max_size = 3 | |
cache.store(:key1,object) | |
cache.store(:key2,object2) | |
cache.store(:key3,object3) | |
cache.fetch(:key1).should eql(object) | |
cache.store(:key4,object4) | |
cache.fetch(:key4).should eql(object4) | |
cache.fetch(:key1).should eql(nil) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment