forked from isisAnchalee/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru-cache.rb
55 lines (46 loc) · 917 Bytes
/
lru-cache.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class LRUCache
def initialize(max, prc)
@map = HashMap.new
@store = LinkedList.new
@max = max
@prc = prc
end
def count
@map.count
end
def get(key)
if @map[key]
link = @map[key]
update_link!(link)
link.val
else
calc!(key)
end
end
def to_s
"Map: " + @map.to_s + "\n" + "Store: " + @store.to_s
end
private
def calc!(key)
val = @prc.call(key)
new_link = @store.insert(key, val)
@map[key] = new_link
eject! if count > @max
val
end
def update_link!(link)
link.prev.next = link.next
link.next.prev = link.prev
link.prev = @store.tail.prev
@store.tail.prev.next = link
link.next = @store.tail
@store.tail.prev = link
end
def eject!
rm_link = @store.head.next
rm_link.prev.next = rm_link.next
rm_link.next.prev = rm_link.prev
@map.delete(rm_link.key)
nil
end
end