Skip to content

Instantly share code, notes, and snippets.

@michel
Created March 23, 2012 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michel/2169470 to your computer and use it in GitHub Desktop.
Save michel/2169470 to your computer and use it in GitHub Desktop.
LRUCache code kata 2
class LRUCache
def initialize(size = 10)
@size = size
@store = {}
@lru = []
end
def set(key, value)
@store[key] = value
set_lru(key)
@store.delete(@lru.pop) if @lru.size > @size
end
def get(key)
set_lru(key)
@store[key]
end
private
def set_lru(key)
@lru.unshift(@lru.delete(key) || key)
end
end
if __FILE__ == $0
require 'test/unit'
class TestLRUCache < Test::Unit::TestCase
def setup
@cache = LRUCache.new(2)
end
def test_last_droped
@cache.set(:a, 'a')
@cache.set(:b, 'b')
@cache.set(:c, 'c')
assert_nil @cache.get(:a)
assert_equal 'b', @cache.get(:b)
assert_equal 'c', @cache.get(:c)
end
def test_get_keeps_key
@cache.set(:a, 'a')
@cache.set(:b, 'b')
@cache.get(:a)
@cache.set(:c, 'c')
assert_equal 'a', @cache.get(:a)
assert_nil @cache.get(:b)
assert_equal 'c', @cache.get(:c)
end
def test_set_keeps_key
@cache.set(:a, 'a')
@cache.set(:b, 'b')
@cache.set(:a, 'a')
@cache.set(:c, 'c')
assert_equal 'a', @cache.get(:a)
assert_nil @cache.get(:b)
assert_equal 'c', @cache.get(:c)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment