Skip to content

Instantly share code, notes, and snippets.

@kenota
Created August 2, 2018 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenota/57c09b92dd74939b8d471f91f715babb to your computer and use it in GitHub Desktop.
Save kenota/57c09b92dd74939b8d471f91f715babb to your computer and use it in GitHub Desktop.
func main() {
m := NewLRUHashMap(3)
m.Put("1", "a")
m.Put("2", "b")
m.Put("3", "c")
m.Put("4", "d")
fmt.Println(m.Get("1"))
fmt.Println(m.Get("4"))
fmt.Println(m.cache)
}
type LRUHashMap struct {
cache map[string]interface{}
queue chan string
max int
}
func NewLRUHashMap(max int) *LRUHashMap {
return &LRUHashMap{
max: max,
cache: map[string]interface{}{},
queue: make(chan string, max),
}
}
func (m *LRUHashMap) Put(k string, val interface{}) {
if _, found := m.cache[k]; found {
tmp := make(chan string, m.max)
close(m.queue)
for key := range m.queue {
if key == k {
continue
}
tmp <- key
}
m.queue = tmp
} else {
if len(m.queue) >= m.max {
key := <-m.queue
delete(m.cache, key)
}
}
m.queue <- k
m.cache[k] = val
}
func (m *LRUHashMap) Get(k string) interface{} {
v, found := m.cache[k]
if !found {
return nil
}
tmp := make(chan string, m.max)
close(m.queue)
for key := range m.queue {
if key == k {
continue
}
tmp <- key
}
tmp <- k
m.queue = tmp
return v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment