Skip to content

Commit

Permalink
feat: add helper cache methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Ismail Gjevori authored May 26, 2022
1 parent de74e40 commit d8591db
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ func (c *LRUCache[K, V]) IterVals() Iterator[V] {
}
}

// IsFull returns true if the cache is full.
func (c *LRUCache[K, V]) IsFull() bool {
return len(c.cached) == c.size && c.size > 0
}

// IsEmpty returns true if the cache is empty.
func (c *LRUCache[K, V]) IsEmpty() bool {
return len(c.cached) == 0
}

// Len returns the number of items in the cache.
func (c *LRUCache[K, V]) Len() int {
return len(c.cached)
Expand Down
37 changes: 37 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,40 @@ func TestCacheReverseIterVales(t *testing.T) {
}
}
}

func TestCacheIsEmpty(t *testing.T) {
cache := NewCache[int, int](3)
if !cache.IsEmpty() {
t.Errorf("cache.IsEmpty() = %t, want %t", cache.IsEmpty(), true)
}
cache.Put(1, 4)
if cache.IsEmpty() {
t.Errorf("cache.IsEmpty() = %t, want %t", cache.IsEmpty(), false)
}
}

func TestCacheIsFullWithSize(t *testing.T) {
cache := NewCache[int, int](3)
if cache.IsFull() {
t.Errorf("cache.IsFull() = %t, want %t", cache.IsFull(), false)
}
cache.Put(1, 4)
cache.Put(2, 5)
cache.Put(3, 6)
if !cache.IsFull() {
t.Errorf("cache.IsFull() = %t, want %t", cache.IsFull(), true)
}
}

func TestCacheIsFullWithoutSize(t *testing.T) {
cache := NewCache[int, int](0)
if cache.IsFull() {
t.Errorf("cache.IsFull() = %t, want %t", cache.IsFull(), false)
}
cache.Put(1, 4)
cache.Put(2, 5)
cache.Put(3, 6)
if cache.IsFull() {
t.Errorf("cache.IsFull() = %t, want %t", cache.IsFull(), false)
}
}

0 comments on commit d8591db

Please sign in to comment.