forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.go
75 lines (64 loc) · 1.55 KB
/
lru.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// lru.go
// description : Least Recently Used (LRU) cache
// details : A Least Recently Used (LRU) cache is a type of cache algorithm used to manage memory within a computer. The LRU algorithm is designed to remove the least recently used items first when the cache reaches its limit.
// time complexity : O(1)
// space complexity : O(n)
// ref : https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
package cache
import (
"github.com/TheAlgorithms/Go/structure/linkedlist"
)
type item struct {
key string
value any
// the frequency of key
freq int
}
type LRU struct {
dl *linkedlist.Doubly[any]
size int
capacity int
storage map[string]*linkedlist.Node[any]
}
// NewLRU represent initiate lru cache with capacity
func NewLRU(capacity int) LRU {
return LRU{
dl: linkedlist.NewDoubly[any](),
storage: make(map[string]*linkedlist.Node[any], capacity),
size: 0,
capacity: capacity,
}
}
// Get value from lru
// if not found, return nil
func (c *LRU) Get(key string) any {
v, ok := c.storage[key]
if ok {
c.dl.MoveToBack(v)
return v.Val.(item).value
}
return nil
}
// Put cache with key and value to lru
func (c *LRU) Put(key string, value any) {
e, ok := c.storage[key]
if ok {
n := e.Val.(item)
n.value = value
e.Val = n
c.dl.MoveToBack(e)
return
}
if c.size >= c.capacity {
e := c.dl.Front()
dk := e.Val.(item).key
c.dl.Remove(e)
delete(c.storage, dk)
c.size--
}
n := item{key: key, value: value}
c.dl.AddAtEnd(n)
ne := c.dl.Back()
c.storage[key] = ne
c.size++
}