Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add remove method, if key exists, delete and return elements #77

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,23 @@ func (c *cache) Delete(k string) {
}
}

// Remove an item from the cache. Does nothing if the key is not in the cache.
// There is delete cache data, return cache data and presence status
func (c *cache) Remove(k string) (interface{}, bool) {
c.mu.Lock()
v, found := c.items[k]
if found {
delete(c.items, k)
c.mu.Unlock()
if c.onEvicted != nil {
c.onEvicted(k, v)
}
return v.Object, true
}
c.mu.Unlock()
return nil, false
}

func (c *cache) delete(k string) (interface{}, bool) {
if c.onEvicted != nil {
if v, found := c.items[k]; found {
Expand Down
18 changes: 18 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1149,7 +1149,25 @@ func TestDelete(t *testing.T) {
t.Error("x is not nil:", x)
}
}
func TestREmove(t *testing.T) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo

tc := New(DefaultExpiration, 0)
tc.Set("foo", "bar", DefaultExpiration)
data, ok := tc.Remove("foo")
if !ok {
t.Error("foo was not found, It should be discovered")
}
if data != "bar" {
t.Error("foo should be bar ")
}

x, found := tc.Get("foo")
if found {
t.Error("foo was found, but it should have been deleted")
}
if x != nil {
t.Error("x is not nil:", x)
}
}
func TestItemCount(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo", "1", DefaultExpiration)
Expand Down