Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Memoize #113

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ func (c *cache) set(k string, x interface{}, d time.Duration) {
}
}

// Lazily compute the given function and store its result item
// to cache. Returns the computed item and a bool indicating
// whether the item was updated.
func (c *cache) Memoize(k string, f func() interface{}, d time.Duration) (interface{}, bool) {
c.mu.Lock()
v, found := c.get(k)
if found {
c.mu.Unlock()
return v, !found
}
v = f()
c.set(k, v, d)
c.mu.Unlock()
return v, !found
}

// Add an item to the cache, replacing any existing item, using the default
// expiration.
func (c *cache) SetDefault(k string, x interface{}) {
Expand Down
23 changes: 23 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,29 @@ func TestStorePointerToStruct(t *testing.T) {
}
}

func TestMemoizeFunction(t *testing.T) {
f := func() interface{} {
return 5
}

tc := New(DefaultExpiration, 0)
x, updated := tc.Memoize("tmemoize", f, DefaultExpiration)
if !updated {
t.Fatal("tmemoize was not updated")
}
if x.(int) != 5 {
t.Fatal("tmemoize is not 5:", x)
}

y, updated := tc.Memoize("tmemoize", f, DefaultExpiration)
if updated {
t.Fatal("tmemoize was updated")
}
if y.(int) != 5 {
t.Fatal("tmemoize is not 5:", y)
}
}

func TestIncrementWithInt(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("tint", 1, DefaultExpiration)
Expand Down