-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrequency.go
61 lines (51 loc) · 1.81 KB
/
frequency.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
package gocache
import (
"container/list"
)
type FrequencyItem struct {
Entries map[*Entry]byte // Set of entries
Freq int // Access frequency
}
func (c *Cache) incrementEntryFrequency(entry *Entry) {
var (
currentFrequency = entry.frequencyParent
nextFrequencyAmount int
nextFrequency *list.Element
)
// if current frequency is nil, we will create with frequency 1
if currentFrequency == nil {
nextFrequencyAmount = 1
nextFrequency = c.freqs.Front()
} else {
// set the next frequency amount to current + 1, since we need to increment the current entry
// frequency and move that to the +1 key in the list
nextFrequencyAmount = currentFrequency.Value.(*FrequencyItem).Freq + 1
nextFrequency = currentFrequency.Next()
}
// if nextFrequency doesnt exist or the key isnt same as the nextFrequencyAmount
// we will create a new key for the entry
if nextFrequency == nil || nextFrequency.Value.(*FrequencyItem).Freq != nextFrequencyAmount {
newFrequencyItem := new(FrequencyItem)
newFrequencyItem.Freq = nextFrequencyAmount
newFrequencyItem.Entries = make(map[*Entry]byte)
if currentFrequency == nil {
nextFrequency = c.freqs.PushFront(newFrequencyItem)
} else {
nextFrequency = c.freqs.InsertAfter(newFrequencyItem, currentFrequency)
}
}
entry.frequencyParent = nextFrequency
nextFrequency.Value.(*FrequencyItem).Entries[entry] = 1
if currentFrequency != nil {
c.removeEntryFromFrequencyList(currentFrequency, entry)
}
}
func (c *Cache) removeEntryFromFrequencyList(listItem *list.Element, item *Entry) {
frequencyItem := listItem.Value.(*FrequencyItem)
// delete entry in the frequency list
delete(frequencyItem.Entries, item)
// if no other cache in the frequency list, remove the frequency
if len(frequencyItem.Entries) == 0 {
c.freqs.Remove(listItem)
}
}