-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemoize.go
51 lines (41 loc) · 1.56 KB
/
memoize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package memoize
import (
"time"
"github.com/patrickmn/go-cache"
"golang.org/x/sync/singleflight"
)
// Memoizer allows you to memoize function calls. Memoizer is safe for concurrent use by multiple goroutines.
type Memoizer struct {
// Storage exposes the underlying cache of memoized results to manipulate as desired - for example, to Flush().
Storage *cache.Cache
group singleflight.Group
}
type functionResult struct {
value interface{}
error error
}
// NewMemoizer creates a new Memoizer with the configured expiry and cleanup policies.
// If desired, use cache.NoExpiration to cache values forever.
func NewMemoizer(defaultExpiration, cleanupInterval time.Duration) *Memoizer {
return &Memoizer{
Storage: cache.New(defaultExpiration, cleanupInterval),
group: singleflight.Group{},
}
}
// Memoize executes and returns the results of the given function, unless there was a cached value of the same key.
// Only one execution is in-flight for a given key at a time.
// The boolean return value indicates whether v was previously stored.
func (m *Memoizer) Memoize(key string, fn func() (interface{}, error)) (interface{}, error, bool) {
// Check cache
result, found := m.Storage.Get(key)
if found {
return result.(functionResult).value, result.(functionResult).error, true
}
// Combine memoized function with a cache store
value, err, _ := m.group.Do(key, func() (interface{}, error) {
data, innerErr := fn()
m.Storage.Set(key, functionResult{value: data, error: innerErr}, cache.DefaultExpiration)
return data, innerErr
})
return value, err, false
}