Skip to content

Commit 5cb6309

Browse files
committed
add Delete() function
1 parent 760ee22 commit 5cb6309

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

example/example.go

+10
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,14 @@ func main() {
9595
}
9696
fmt.Println("ttlMap length:", t.Len())
9797
fmt.Println()
98+
99+
fmt.Println()
100+
fmt.Printf("Manually deleting '%v' key; should be successful\n", dontExpireKey)
101+
success := t.Delete(ttlMap.CustomKeyType(dontExpireKey))
102+
fmt.Printf(" successful? %v\n", success)
103+
fmt.Printf("Manually deleting '%v' key again; should NOT be successful this time\n", dontExpireKey)
104+
success = t.Delete(ttlMap.CustomKeyType(dontExpireKey))
105+
fmt.Printf(" successful? %v\n", success)
106+
fmt.Println("ttlMap length:", t.Len())
107+
fmt.Println()
98108
}

ttlMap.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import (
3030
"time"
3131
)
3232

33-
const version string = "1.0.0"
33+
const version string = "1.1.0"
3434

3535
type CustomKeyType string
3636

@@ -96,6 +96,18 @@ func (m *ttlMap) Get(k CustomKeyType) (v interface{}) {
9696
return
9797
}
9898

99+
func (m *ttlMap) Delete(k CustomKeyType) bool {
100+
m.l.Lock()
101+
_, ok := m.m[k]
102+
if !ok {
103+
m.l.Unlock()
104+
return false
105+
}
106+
delete(m.m, k)
107+
m.l.Unlock()
108+
return true
109+
}
110+
99111
func (m *ttlMap) All() map[CustomKeyType]*item {
100112
return m.m
101113
}

ttlMap_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,27 @@ func TestWithNoRefresh(t *testing.T) {
100100
t.Errorf("t.Len should be 0, but actually equals %v\n", tm.Len())
101101
}
102102
}
103+
104+
func TestDelete(t *testing.T) {
105+
maxTTL := 2 // time in seconds
106+
startSize := 3 // initial number of items in map
107+
pruneInterval := 4 // search for expired items every 'pruneInterval' seconds
108+
refreshLastAccessOnGet := true // update item's lastAccessTime on a .Get()
109+
tm := New(maxTTL, startSize, pruneInterval, refreshLastAccessOnGet)
110+
111+
// populate the ttlMap
112+
tm.Put("myString", "a b c")
113+
tm.Put("int_array", []int{1, 2, 3})
114+
115+
tm.Delete("int_array")
116+
t.Logf("tm.len: %v\n", tm.Len())
117+
if tm.Len() != 1 {
118+
t.Fatalf("t.Len should equal 1, but actually equals %v\n", tm.Len())
119+
}
120+
121+
tm.Delete("myString")
122+
t.Logf("tm.len: %v\n", tm.Len())
123+
if tm.Len() != 0 {
124+
t.Fatalf("t.Len should equal 0, but actually equals %v\n", tm.Len())
125+
}
126+
}

0 commit comments

Comments
 (0)