Skip to content

Commit

Permalink
Add Linkedmap library
Browse files Browse the repository at this point in the history
  • Loading branch information
themantre committed Nov 30, 2020
1 parent 36f3968 commit b05d699
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 0 deletions.
79 changes: 79 additions & 0 deletions libs/linkedmap/linkedmap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package linkedmap

import (
"container/list"
)

type pair struct {
key, value interface{}
}

type LinkedMap struct {
list *list.List
hashmap map[interface{}]*list.Element
capacity int
}

func NewLinkedMap(capacity int) *LinkedMap {
return &LinkedMap{
list: list.New(),
hashmap: make(map[interface{}]*list.Element),
capacity: capacity,
}
}

func (lm *LinkedMap) SetCapacity(capacity int) {
lm.capacity = capacity
}

func (lm *LinkedMap) Has(key interface{}) bool {
_, found := lm.hashmap[key]
return found
}

func (lm *LinkedMap) PushBack(key interface{}, value interface{}) {
_, found := lm.hashmap[key]
if found {
return
}

if lm.list.Len() == lm.capacity {
front := lm.list.Front()
key := front.Value.(pair).key
lm.list.Remove(front)
delete(lm.hashmap, key)
}

el := lm.list.PushBack(pair{key, value})
lm.hashmap[key] = el
}

func (lm *LinkedMap) Get(key interface{}) (interface{}, bool) {
el, found := lm.hashmap[key]
if found {
return el.Value.(pair).value, true

}
return nil, false
}

func (lm *LinkedMap) Remove(key interface{}) {
el, found := lm.hashmap[key]
if found {
lm.list.Remove(el)
delete(lm.hashmap, el.Value.(pair).key)
}
}

func (lm *LinkedMap) Empty() bool {
return lm.Size() == 0
}

func (lm *LinkedMap) Size() int {
return lm.list.Len()
}

func (lm *LinkedMap) Clear() {
lm.list = list.New()
lm.hashmap = make(map[interface{}]*list.Element)
}
45 changes: 45 additions & 0 deletions libs/linkedmap/linkedmap_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package linkedmap

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestLinkedMap(t *testing.T) {
lm := NewLinkedMap(4)

assert.True(t, lm.Empty())
lm.PushBack(2, "b")
lm.PushBack(1, "a")

value, found := lm.Get(2)
assert.Equal(t, found, true)
assert.Equal(t, value, "b")

value, found = lm.Get(5)
assert.Equal(t, found, false)
assert.Equal(t, value, nil)

lm.Remove(2)

value, found = lm.Get(2)
assert.Equal(t, found, false)
assert.Equal(t, value, nil)

lm.PushBack(3, "c")
lm.PushBack(3, "c")
assert.Equal(t, lm.Size(), 2)

lm.PushBack(4, "d")
lm.PushBack(5, "e")

value, found = lm.Get(1)
assert.Equal(t, found, true)
assert.Equal(t, value, "a")
lm.PushBack(6, "f")

value, found = lm.Get(1)
assert.Equal(t, found, false)
assert.Equal(t, value, nil)
}

0 comments on commit b05d699

Please sign in to comment.