lfu

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2023 License: MIT Imports: 3 Imported by: 8

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is used a LFU (Least-frequently used) cache replacement policy.

Counts how often an item is needed. Those that are used least often are discarded first. This works very similar to LRU except that instead of storing the value of how recently a block was accessed, we store the value of how many times it was accessed. So of course while running an access sequence we will replace a block which was used fewest times from our cache.

func NewCache

func NewCache[K comparable, V any](opts ...Option) *Cache[K, V]

NewCache creates a new non-thread safe LFU cache whose capacity is the default size (128).

Example
package main

import (
	"fmt"

	"github.com/Code-Hex/go-generics-cache/policy/lfu"
)

func main() {
	c := lfu.NewCache[string, int]()
	c.Set("a", 1)
	c.Set("b", 2)
	av, aok := c.Get("a")
	bv, bok := c.Get("b")
	cv, cok := c.Get("c")
	fmt.Println(av, aok)
	fmt.Println(bv, bok)
	fmt.Println(cv, cok)
}
Output:

1 true
2 true
0 false

func (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(key K)

Delete deletes the item with provided key from the cache.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (zero V, _ bool)

Get looks up a key's value from the cache.

func (*Cache[K, V]) Keys

func (c *Cache[K, V]) Keys() []K

Keys returns the keys of the cache. the order is from oldest to newest.

Example
package main

import (
	"fmt"

	"github.com/Code-Hex/go-generics-cache/policy/lfu"
)

func main() {
	c := lfu.NewCache[string, int]()
	c.Set("a", 1)
	c.Set("b", 2)
	c.Set("c", 3)
	keys := c.Keys()
	for _, key := range keys {
		fmt.Println(key)
	}
}
Output:

a
b
c

func (*Cache[K, V]) Len

func (c *Cache[K, V]) Len() int

Len returns the number of items in the cache.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, val V)

Set sets a value to the cache with key. replacing any existing value.

If value satisfies "interface{ GetReferenceCount() int }", the value of the GetReferenceCount() method is used to set the initial value of reference count.

type Option

type Option func(*options)

Option is an option for LFU cache.

func WithCapacity

func WithCapacity(cap int) Option

WithCapacity is an option to set cache capacity.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL