Created
August 2, 2018 16:14
-
-
Save kenota/57c09b92dd74939b8d471f91f715babb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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