/ Published in: Ruby
Expand |
Embed | Plain Text
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
Comments
Subscribe to comments
You need to login to post a comment.

"@lru.delete(key)" on line 22 is an O(n) search. Doesn't matter when n is small, but can be very non-performant if n is big.