memoizer

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2023 License: MIT Imports: 2 Imported by: 0

README

go-memoizer

A simple thread-safe memoizer for Go using only the standard library.

Supports Go 1.18 and higher due to the use of generics.

Reference Linter Build status

func expensiveFunction() (*any, error) {
    // ...
}

var memoized = memoizer.New(expensiveFunction, 10*time.Second)

for i := 0; i < 50; i++ {
    value, err := memoized.Get()

    // ...
}

Installation

go get github.com/LightningDev1/go-memoizer

Usage

See config example for a complete example program.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Memoizer

type Memoizer[T any] struct {
	// The function to call to get the value.
	Function func() (*T, error)

	// The time after which the value should be invalidated.
	InvalidateAfter time.Duration

	// The time at which the value was last loaded.
	LastLoaded time.Time

	// The mutex to use for locking.
	Mutex sync.RWMutex

	// The value of the memoizer.
	Value *T
}

Memoizer can cache a value for a certain amount of time. Used for caching a function return value.

func New

func New[T any](function func() (*T, error), invalidateAfter time.Duration) *Memoizer[T]

New creates a new memoizer.

func (*Memoizer[T]) Get

func (m *Memoizer[T]) Get() (*T, error)

Get gets the value of the memoizer. If the value is not cached, it will call the function to get the value.

func (*Memoizer[T]) GetCacheValue

func (m *Memoizer[T]) GetCacheValue() *T

GetCacheValue gets the current cached value.

func (*Memoizer[T]) InvalidateTime

func (m *Memoizer[T]) InvalidateTime() time.Time

InvalidateTime returns the time after which the value should be invalidated.

func (*Memoizer[T]) LoadValue

func (m *Memoizer[T]) LoadValue() (*T, error)

LoadValue loads the value from the function.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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