diff --git a/gotcha.go b/gotcha.go index 2079f2c..fb2b66c 100644 --- a/gotcha.go +++ b/gotcha.go @@ -157,6 +157,28 @@ func (g *Gotcha) Expired(index interface{}) bool { return it != nil && expired(it) } +// Cleanup removes all expired data +func (g *Gotcha) Cleanup() { + g.m.Lock() + defer g.m.Unlock() + for index, it := range g.d { + if expired(it) { + delete(g.d, index) + } + } +} + +// Timestamp returns timestamp of an index +func (g *Gotcha) Timestamp(index interface{}) *time.Time { + g.m.RLock() + defer g.m.RUnlock() + it := g.d[index] + if it == nil { + return nil + } + return &it.ts +} + // helper funcitons func expired(it *item) bool { if it.ttl <= 0 { diff --git a/gotcha_test.go b/gotcha_test.go index c0e46f2..c971c5a 100644 --- a/gotcha_test.go +++ b/gotcha_test.go @@ -121,3 +121,30 @@ func TestExpired(t *testing.T) { t.Errorf("expected 1 expired") } } + +func TestCleanup(t *testing.T) { + g := New() + g.SetTTL(1, 2, time.Millisecond*10) + g.SetTTL(2, 3, time.Millisecond*20) + time.Sleep(time.Millisecond * 15) + g.Cleanup() + if g.Exists(1) { + t.Errorf("expected 1 not exists") + } + if !g.Exists(2) { + t.Errorf("expected 2 exists") + } +} + +func TestTimestamp(t *testing.T) { + g := New() + g.SetTTL(1, 2, time.Millisecond*10) + ts := g.Timestamp(1) + if ts == nil { + t.Errorf("expected timestamp not nil") + } + ts = g.Timestamp(2) + if ts != nil { + t.Errorf("expected timestamp to be nil") + } +}