Skip to content

Commit

Permalink
functional options, WithCleanup is for setting interval and starting …
Browse files Browse the repository at this point in the history
…Cleanup goroutine
  • Loading branch information
parMaster committed Aug 4, 2023
1 parent 5235e39 commit 53ff554
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
28 changes: 23 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (

// Errors for cache
const (
ErrKeyNotFound = "Key not found"
ErrKeyExists = "Key already exists"
ErrExpired = "Key expired"
ErrKeyNotFound = "key not found"
ErrKeyExists = "key already exists"
ErrExpired = "key expired"
)

// CacheItem is a struct for cache item
Expand All @@ -36,10 +36,16 @@ type Cacher interface {
}

// NewCache is a constructor for Cache
func NewCache() *Cache {
return &Cache{
func NewCache(options ...func(*Cache)) *Cache {
c := &Cache{
data: make(map[string]CacheItem),
}

for _, option := range options {
option(c)
}

return c
}

// Set is a method for setting key-value pair
Expand Down Expand Up @@ -143,3 +149,15 @@ func (c *Cache) Cleanup() {
}
c.mx.Unlock()
}

// WithCleanup is a functional option for setting interval and starting Cleanup goroutine
func WithCleanup(ttl int64) func(*Cache) {
return func(c *Cache) {
go func() {
for {
c.Cleanup()
time.Sleep(time.Duration(ttl) * time.Second)
}
}()
}
}
21 changes: 21 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ func Test_SimpleTest_Mcache(t *testing.T) {
// key should be deleted
has, err = c.Has("key")
assert.False(t, has)
assert.Error(t, err)

// del should return error if key doesn't exist
err = c.Del("noSuchKey")
Expand Down Expand Up @@ -145,6 +146,26 @@ func TestConcurrentSetAndGet(t *testing.T) {
}
}

// TestWithCleanup tests that the cleanup goroutine is working
func TestWithCleanup(t *testing.T) {
cache := NewCache(WithCleanup(1))

// Set a value with a TTL of 1 second
err := cache.Set("key", "value", 1)
if err != nil {
t.Errorf("Error setting value for key: %s", err)
}

// Wait for 2 seconds
time.Sleep(2 * time.Second)

// Check that the value has been deleted
_, err = cache.Get("key")
if err == nil {
t.Errorf("Expected error getting value for key, but got nil")
}
}

func TestMain(m *testing.M) {
// Enable the race detector
m.Run()
Expand Down

0 comments on commit 53ff554

Please sign in to comment.