Skip to content

Instantly share code, notes, and snippets.

@tomoya55
Created December 19, 2009 09:39
Show Gist options
  • Select an option

  • Save tomoya55/260025 to your computer and use it in GitHub Desktop.

Select an option

Save tomoya55/260025 to your computer and use it in GitHub Desktop.
class Array
def move_to_last(val)
self.delete(val)
self.push(val)
end
end
class LRUCache
attr_reader :cache_size
attr_accessor :store_seconds
def initialize(options)
@cache_size = options[:cache_size] || 2
@store_seconds = options[:store_seconds] || 1
@queue = []
end
def cache_size=(size)
if size < @cache_size
@queue = @queue[(@cache_size - size) .. -1]
end
@cache_size = size
end
#[[key3, atime, value], [key1, atime, value3], [key4, atime, value], [key1, atime, value]]
def put(key, value)
new_item = [key, Time.now, value]
if (existing_item = get_item(key))
@queue.delete(existing_item)
end
@queue << new_item
delete_oldest_cache
new_item
end
# alias :[]= :put
def get(key)
delete_old_cache
item = get_item(key)
item ? item.last : nil
end
# alias :[] :get
private
def get_item(key)
value = @queue.assoc(key)
return nil unless value
@queue.move_to_last(value)
value
end
def get_atime(key)
value = @queue.assoc(key)
return nil unless value
value[1]
end
def delete_oldest_cache
if @queue.size > @cache_size
@queue.shift
end
end
def delete_old_cache
now = Time.now
@queue.delete_if do |item|
(now - item[1]).to_i > @store_seconds
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment