-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (66 loc) · 1.45 KB
/
main.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
package main
import (
"errors"
"fmt"
"lruCache/dbllinkedlist"
)
type LRUCache struct {
capacity int
held int
log *dbllinkedlist.DblLinkedList
cache *map[string]*dbllinkedlist.Node
}
func NewLRUCache(cap int) *LRUCache {
return &LRUCache{
capacity: cap,
log: &dbllinkedlist.DblLinkedList{},
cache: &map[string]*dbllinkedlist.Node{},
}
}
func (l *LRUCache) Get(key string) (interface{}, bool) {
store := *l.cache
node, ok := store[key]
if ok {
/* bump key to top of list */
l.log.DeleteNode(node)
l.log.SetListHead(node)
/* return data held by the node */
return node.Value, ok
}
return nil, false
}
func (l *LRUCache) Set(key string, data interface{}) error {
store := *l.cache
_, prs := store[key]
node := &dbllinkedlist.Node{Key: key, Value: data}
if l.held < l.capacity {
store[key] = node
l.log.SetListHead(node)
l.held++
return nil
} else if l.held == l.capacity && prs {
store[key] = node
l.log.DeleteNode(node)
l.log.SetListHead(node)
return nil
} else if l.held == l.capacity && !prs {
store[key] = node
delete(store, l.log.Tail.Key)
l.log.DeleteListTail()
l.log.SetListHead(node)
return nil
}
return errors.New("improper cache state")
}
func main() {
cache := NewLRUCache(2)
cache.Set("first", 1)
cache.Set("next", 2)
cache.Set("third", 3)
item, err := cache.Get("first")
fmt.Println(item)
fmt.Println(err)
item, err = cache.Get("next")
fmt.Println(item)
fmt.Println(err)
}