Class: Tins::LRUCache

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/tins/lru_cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity) ⇒ LRUCache

Returns a new instance of LRUCache.



15
16
17
18
# File 'lib/tins/lru_cache.rb', line 15

def initialize(capacity)
  @capacity = capacity
  @data     = {}
end

Instance Attribute Details

#capacityObject (readonly)

Returns the value of attribute capacity.



20
21
22
# File 'lib/tins/lru_cache.rb', line 20

def capacity
  @capacity
end

Instance Method Details

#[](key) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/tins/lru_cache.rb', line 22

def [](key)
  case value = @data.delete(key){ not_exist }
  when not_exist
    nil
  else
    @data[key] = value
  end
end

#[]=(key, value) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/tins/lru_cache.rb', line 31

def []=(key, value)
  @data.delete(key)
  @data[key] = value
  if @data.size > @capacity
    @data.delete(@data.keys.first)
  end
  value
end

#clearObject



48
49
50
# File 'lib/tins/lru_cache.rb', line 48

def clear
  @data.clear
end

#delete(key) ⇒ Object



44
45
46
# File 'lib/tins/lru_cache.rb', line 44

def delete(key)
  @data.delete(key)
end

#each(&block) ⇒ Object



40
41
42
# File 'lib/tins/lru_cache.rb', line 40

def each(&block)
  @data.reverse_each(&block)
end

#sizeObject



52
53
54
# File 'lib/tins/lru_cache.rb', line 52

def size
  @data.size
end