Skip to content

Commit

Permalink
add Delete() function
Browse files Browse the repository at this point in the history
  • Loading branch information
jftuga committed Oct 23, 2023
1 parent 760ee22 commit 5cb6309
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
10 changes: 10 additions & 0 deletions example/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,14 @@ func main() {
}
fmt.Println("ttlMap length:", t.Len())
fmt.Println()

fmt.Println()
fmt.Printf("Manually deleting '%v' key; should be successful\n", dontExpireKey)
success := t.Delete(ttlMap.CustomKeyType(dontExpireKey))
fmt.Printf(" successful? %v\n", success)
fmt.Printf("Manually deleting '%v' key again; should NOT be successful this time\n", dontExpireKey)
success = t.Delete(ttlMap.CustomKeyType(dontExpireKey))
fmt.Printf(" successful? %v\n", success)
fmt.Println("ttlMap length:", t.Len())
fmt.Println()
}
14 changes: 13 additions & 1 deletion ttlMap.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (
"time"
)

const version string = "1.0.0"
const version string = "1.1.0"

type CustomKeyType string

Expand Down Expand Up @@ -96,6 +96,18 @@ func (m *ttlMap) Get(k CustomKeyType) (v interface{}) {
return
}

func (m *ttlMap) Delete(k CustomKeyType) bool {
m.l.Lock()
_, ok := m.m[k]
if !ok {
m.l.Unlock()
return false
}
delete(m.m, k)
m.l.Unlock()
return true
}

func (m *ttlMap) All() map[CustomKeyType]*item {
return m.m
}
24 changes: 24 additions & 0 deletions ttlMap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,27 @@ func TestWithNoRefresh(t *testing.T) {
t.Errorf("t.Len should be 0, but actually equals %v\n", tm.Len())
}
}

func TestDelete(t *testing.T) {
maxTTL := 2 // time in seconds
startSize := 3 // initial number of items in map
pruneInterval := 4 // search for expired items every 'pruneInterval' seconds
refreshLastAccessOnGet := true // update item's lastAccessTime on a .Get()
tm := New(maxTTL, startSize, pruneInterval, refreshLastAccessOnGet)

// populate the ttlMap
tm.Put("myString", "a b c")
tm.Put("int_array", []int{1, 2, 3})

tm.Delete("int_array")
t.Logf("tm.len: %v\n", tm.Len())
if tm.Len() != 1 {
t.Fatalf("t.Len should equal 1, but actually equals %v\n", tm.Len())
}

tm.Delete("myString")
t.Logf("tm.len: %v\n", tm.Len())
if tm.Len() != 0 {
t.Fatalf("t.Len should equal 0, but actually equals %v\n", tm.Len())
}
}

0 comments on commit 5cb6309

Please sign in to comment.