Put the key in LFU cache
(key string, value any)
| 65 | |
| 66 | // Put the key in LFU cache |
| 67 | func (c *LFU) Put(key string, value any) { |
| 68 | if e, ok := c.itemMap[key]; ok { |
| 69 | // if key existed, update the value |
| 70 | obj := e.Value.(item) |
| 71 | obj.value = value |
| 72 | c.increaseFreq(e) |
| 73 | } else { |
| 74 | // if key not existed |
| 75 | obj := initItem(key, value, 1) |
| 76 | // if the length of item gets to the top line |
| 77 | // remove the least frequently operated element |
| 78 | if c.len == c.cap { |
| 79 | c.eliminate() |
| 80 | c.len-- |
| 81 | } |
| 82 | // insert in freqMap and itemMap |
| 83 | c.insertMap(obj) |
| 84 | // change minFreq to 1 because insert the newest one |
| 85 | c.minFreq = 1 |
| 86 | // length++ |
| 87 | c.len++ |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // increaseFreq increase the frequency if element |
| 92 | func (c *LFU) increaseFreq(e *list.Element) { |