Skip to content

Commit

Permalink
Add a GetDefault method.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeremy Bowers authored and Code-Hex committed Apr 13, 2024
1 parent 5303a9a commit 40763d5
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,22 @@ func (c *Cache[K, V]) Get(key K) (zero V, ok bool) {
return item.Value, true
}

// GetDefault atomically gets a key's value from the cache, or if the
// key is not present, sets the given value.
func (c *Cache[K, V]) GetDefault(key K, val V, opts ...ItemOption) V {
c.mu.Lock()
defer c.mu.Unlock()
item, ok := c.cache.Get(key)

if !ok || item.Expired() {
item := newItem(key, val, opts...)
c.cache.Set(key, item)
return val
}

return item.Value
}

// DeleteExpired all expired items from the cache.
func (c *Cache[K, V]) DeleteExpired() {
c.mu.Lock()
Expand Down

0 comments on commit 40763d5

Please sign in to comment.