From 9b5a155a44707a2072d89ae9256c440e32c98a74 Mon Sep 17 00:00:00 2001 From: rjbasitali Date: Tue, 5 Apr 2022 16:55:25 +0500 Subject: [PATCH] decision function to evict cache on expiration --- delete_expired.go | 3 +++ my_cache.go | 14 ++++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/delete_expired.go b/delete_expired.go index 954360c..8c51817 100644 --- a/delete_expired.go +++ b/delete_expired.go @@ -8,6 +8,9 @@ func (cache *myCache) deleteExpired() { now := time.Now().UnixNano() for k, v := range cache.items { + if cache.decisionFunc != nil && !cache.decisionFunc(v) { + continue + } if v.expiration > 0 && now > v.expiration { delete(cache.items, k) } diff --git a/my_cache.go b/my_cache.go index 3e115fc..4264bf0 100644 --- a/my_cache.go +++ b/my_cache.go @@ -7,9 +7,10 @@ import ( ) type myCache struct { - mutex sync.Mutex - items map[string]*value - expireAfter int64 + mutex sync.Mutex + items map[string]*value + expireAfter int64 + decisionFunc func(v interface{}) bool } func NewCache() Cache { @@ -18,10 +19,11 @@ func NewCache() Cache { } } -func NewCacheWithSweeper(interval, expireAfter time.Duration) Cache { +func NewCacheWithSweeper(interval, expireAfter time.Duration, decisionFunc func(v interface{}) bool) Cache { c := &myCache{ - items: make(map[string]*value), - expireAfter: expireAfter.Nanoseconds(), + items: make(map[string]*value), + expireAfter: expireAfter.Nanoseconds(), + decisionFunc: decisionFunc, } if interval > 0 && expireAfter > 0 {