Compare commits

...

2 Commits

Author SHA1 Message Date
HuangJiaLuo ee8c3d42e8 Test 2021-09-05 22:48:01 +08:00
HuangJiaLuo f7abb56e92 Test 2021-08-21 22:27:00 +08:00
4 changed files with 129 additions and 1 deletions

110
pkg/lru/LRU.go Normal file
View File

@ -0,0 +1,110 @@
package main
import (
"container/list"
"fmt"
)
type Node struct {
Key, Value interface{}
}
func (*Node) NewCacheNode(k, v interface{}) *Node {
return &Node{k, v}
}
type LRUCache struct {
maxsize int //最大的长度
li *list.List
LruMap map[interface{}]*list.Element
}
// lru初始化
func NewLRUCache(size int) *LRUCache {
return &LRUCache{
maxsize: size,
li: list.New(),
LruMap: make(map[interface{}]*list.Element)}
}
//返回lru的长度
func (lru *LRUCache) GetSize() int {
return lru.li.Len()
}
//增
func (lru *LRUCache) Add(k, v interface{}) error {
if lru.li == nil {
return nil
}
if PreEle, ok := lru.LruMap[k]; ok {
lru.li.MoveToFront(PreEle)
PreEle.Value.(*Node).Value = v
return nil
}
newEle := lru.li.PushFront(&Node{k, v})
lru.LruMap[k] = newEle
//超过最长就删
if lru.li.Len() > lru.maxsize {
// 去掉最后一个
last := lru.li.Back()
if last == nil {
return nil
}
Node := last.Value.(*Node)
delete(lru.LruMap, Node.Key)
lru.li.Remove(last)
}
return nil
}
//查
func (lru *LRUCache) Get(k interface{}) (v interface{}, ret bool) {
if lru.LruMap == nil {
return v, false
}
if PreEle, ok := lru.LruMap[k]; ok {
// 移到最前面
lru.li.MoveToFront(PreEle)
return PreEle.Value.(*Node).Value, true
}
return v, false
}
//删
func (lru *LRUCache) Remove(k interface{}) bool {
if lru.LruMap == nil {
return false
}
if PreEle, ok := lru.LruMap[k]; ok {
cacheNode := PreEle.Value.(*Node)
delete(lru.LruMap, cacheNode.Key)
lru.li.Remove(PreEle)
return true
}
return false
}
func main() {
lru := NewLRUCache(3)
lru.Add(10, "test1")
lru.Add(20, "test2")
lru.Add(30, "test3")
v, ret := lru.Get(10)
if ret {
fmt.Println(v)
}
lru.Add(40, "test4")
v, ret = lru.Get(20)
if ret {
fmt.Println(v)
}
}

View File

@ -1,3 +1,5 @@
package define
// define
const (
MaxByte = 1024
)

5
pkg/lru/test/Hello.go Normal file
View File

@ -0,0 +1,5 @@
package test
func Hello(str string) (bool, error) {
return str == "Hello", nil
}

11
pkg/lru/test/HelloTest.go Normal file
View File

@ -0,0 +1,11 @@
package test
import (
"github.com/stretchr/testify/require"
"testing"
)
func TestHello(t *testing.T) {
_, err := Hello("Hello")
require.NoError(t, err)
}