memoizer

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2025 License: MIT Imports: 4 Imported by: 0

README

memoizer

A Go package for memoizing function results. This package provides a simple Memoizer struct that caches the results of a function based on its input parameters, improving the performance of expensive or repetitive function calls.

Features

  • Thread-safe caching mechanism
  • Easy to integrate with existing functions
  • Handles errors gracefully

Installation

To install the package, run:

go get github.com/KevinWang15/memoizer

Usage

Here is a simple example of how to use the Memoizer package:

func TestMemoizer_Memoize(t *testing.T) {
	memoizer := NewMemoizer[int]()

	// Test case 1: Successful memoization
	result1, err1 := memoizer.Memoize("key1", func() (int, error) {
		return 42, nil
	})
	assert.NoError(t, err1)
	assert.Equal(t, 42, result1)

	// Test case 2: Cached result retrieval
	result2, err2 := memoizer.Memoize("key1", func() (int, error) {
		return 0, errors.New("error occurred")
	})
	assert.NoError(t, err2)
	assert.Equal(t, 42, result2)

	// Test case 3: Error handling
	_, err3 := memoizer.Memoize("key2", func() (int, error) {
		return 0, errors.New("error occurred")
	})
	assert.Error(t, err3)

	// Test case 4: Concurrent memoization
	resultChan := make(chan int)
	errChan := make(chan error)
	actualInvocations := 0

	for i := 0; i < 5; i++ {
		go func() {
			result, err := memoizer.Memoize("key3", func() (int, error) {
				actualInvocations++
				return 100, nil
			})
			resultChan <- result
			errChan <- err
		}()
	}

	for i := 0; i < 5; i++ {
		result := <-resultChan
		err := <-errChan
		assert.NoError(t, err)
		assert.Equal(t, 100, result)
		assert.Equal(t, 1, actualInvocations)
	}
}

Testing

To run the tests, use:

go test ./...

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var WithExpiration = func(callback func(result interface{}) time.Duration) Option {
	return &ExpirationOption{Callback: callback}
}

WithExpiration returns an Option that sets a dynamic expiration time for cached results. The provided callback function is called with the result of the memoized function and should return a time.Duration indicating how long the result should be cached.

Example usage:

memoizer.Memoize("key", myFunc, memoizer.WithExpiration(func(result interface{}) time.Duration {
    // Custom logic to determine expiration based on the result
    return time.Hour
}))

Functions

This section is empty.

Types

type ExpirationOption added in v1.0.2

type ExpirationOption struct {
	Callback func(result interface{}) time.Duration
}

ExpirationOption is a struct that implements the Option interface. It contains a Callback function that determines the expiration duration for a cached result based on the result itself.

type Memoizer

type Memoizer[T any] struct {
	// contains filtered or unexported fields
}

Memoizer is a structure that provides memoization capabilities. It stores results of expensive function calls and returns the cached result when possible.

func NewMemoizer

func NewMemoizer[T any]() *Memoizer[T]

NewMemoizer creates and returns a new instance of a Memoizer.

func NewMemoizerWithCacheExpiration

func NewMemoizerWithCacheExpiration[T any](expiration time.Duration) *Memoizer[T]

NewMemoizerWithCacheExpiration creates and returns a new instance of a Memoizer with a specified cache expiration time.

func (*Memoizer[T]) Memoize

func (m *Memoizer[T]) Memoize(key string, fn func() (T, error), options ...Option) (T, error)

Memoize checks the cache for a stored result for the given key. If not found, it executes the function, caches its result, and returns it. This method ensures that concurrent calls with the same key do not result in multiple executions of the function.

type Option added in v1.0.2

type Option interface {
}

Option is an interface for configuring the Memoizer's behavior. Implementations of this interface can be passed to the Memoize function to customize its operation.

Jump to

Keyboard shortcuts

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