Created
May 8, 2022 17:30
-
-
Save ofonimefrancis/77d0546b687c3f608275d4be0d0318f0 to your computer and use it in GitHub Desktop.
Implementing an LRU Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"container/list" | |
"sync" | |
) | |
type LRUCache struct { | |
lock sync.Mutex | |
cache map[int]*list.Element | |
ll *list.List | |
capacity int | |
} | |
type entry struct { | |
key int | |
value int | |
} | |
func Constructor(capacity int) LRUCache { | |
return LRUCache{ | |
cache: make(map[int]*list.Element), | |
ll: list.New(), | |
capacity: capacity, | |
} | |
} | |
func (c *LRUCache) Get(key int) int { | |
//Check if the key exist in the cache | |
c.lock.Lock() | |
defer c.lock.Unlock() | |
if el, ok := c.cache[key]; ok { | |
c.ll.MoveToFront(el) | |
return el.Value.(*entry).value | |
} | |
return -1 | |
} | |
func (c *LRUCache) Put(key int, value int) { | |
//Checks if the item is already in cache | |
//If the item is found in cache, move the item to the front | |
c.lock.Lock() | |
defer c.lock.Unlock() | |
if element, ok := c.cache[key]; ok { | |
c.ll.MoveToFront(element) | |
element.Value.(*entry).value = value | |
return | |
} | |
e := c.ll.PushFront(&entry{key: key, value: value}) | |
c.cache[key] = e | |
if c.ll.Len() > c.capacity && c.capacity > 0 { | |
c.removeOld() | |
} | |
} | |
func (c *LRUCache) removeOld() (int, int) { | |
el := c.ll.Back() | |
if el == nil { | |
return -1, -1 | |
} | |
//Remove the element from the cache and also from the linked list | |
c.ll.Remove(el) | |
elVal := el.Value.(*entry) | |
delete(c.cache, elVal.key) | |
return elVal.key, elVal.value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment