Class: LRUCache
- Inherits:
-
Object
- Object
- LRUCache
- Defined in:
- lib/lru_cache.rb
Direct Known Subclasses
Defined Under Namespace
Classes: Node, ThreadSafe
Constant Summary collapse
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
-
#limit ⇒ Object
Returns the value of attribute limit.
Instance Method Summary collapse
-
#clear ⇒ Object
Empties the cache of all values.
-
#delete(key) ⇒ Object
Remove and return value from cache.
-
#get(key) ⇒ Object
(also: #[])
Return value from cache and sets it as most-recently-used.
-
#initialize(limit = nil) ⇒ LRUCache
constructor
Sets up the new cache, optionally assigning given limit.
-
#set(key, value) ⇒ Object
(also: #[]=)
Stores a value in the cache.
Constructor Details
#initialize(limit = nil) ⇒ LRUCache
Sets up the new cache, optionally assigning given limit.
12 13 14 15 16 |
# File 'lib/lru_cache.rb', line 12 def initialize(limit=nil) @index = {} @count = 0 self.limit = limit if limit end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
9 10 11 |
# File 'lib/lru_cache.rb', line 9 def count @count end |
#limit ⇒ Object
Returns the value of attribute limit.
9 10 11 |
# File 'lib/lru_cache.rb', line 9 def limit @limit end |
Instance Method Details
#clear ⇒ Object
Empties the cache of all values.
19 20 21 |
# File 'lib/lru_cache.rb', line 19 def clear count.times.each { delete_lru } end |
#delete(key) ⇒ Object
Remove and return value from cache.
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/lru_cache.rb', line 24 def delete(key) node = @index.delete(key) return unless node @count -= 1 node.mru.lru = node.lru if node.mru node.lru.mru = node.mru if node.lru @mru = node.lru if @mru == node @lru = node.mru if @lru == node node.value end |
#get(key) ⇒ Object Also known as: []
Return value from cache and sets it as most-recently-used.
36 37 38 39 40 41 42 |
# File 'lib/lru_cache.rb', line 36 def get(key) node = @index[key] if node set_mru(node) node.value end end |
#set(key, value) ⇒ Object Also known as: []=
Stores a value in the cache.
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/lru_cache.rb', line 54 def set(key, value) node = @index[key] unless node node = Node.new(key) @index[key] = node @count += 1 delete_lru if count > ensure_limit end set_mru(node) node.value = value end |