-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemoize.go
More file actions
36 lines (29 loc) · 710 Bytes
/
memoize.go
File metadata and controls
36 lines (29 loc) · 710 Bytes
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
package memoize
import (
"sync"
"github.com/emad-elsaid/memoize/cache"
)
// Memoizer memoizes func(In) Out function
type Memoizer[In any, Out any] struct {
cache cache.Cache[In, func() Out]
Fun func(In) Out
}
// Do calls the memoized function with input i and memoize the result and return it
func (m *Memoizer[In, Out]) Do(i In) Out {
once, ok := m.cache.Load(i)
if !ok {
once, _ = m.cache.LoadOrStore(i,
sync.OnceValue(
func() Out { return m.Fun(i) },
),
)
}
return once()
}
// New creates a new memoizer wrapping func and returning the Memoizer Do function directly
func New[In, Out any](fun func(In) Out) func(In) Out {
m := Memoizer[In, Out]{
Fun: fun,
}
return m.Do
}