-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
68 lines (56 loc) · 1 KB
/
slice.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package kash
import (
"time"
"fmt"
)
type SliceCache struct {
data []interface{}
loader func() []interface{}
ttl time.Duration
}
func NewSliceCache() *SliceCache {
nilSliceLoader := func() []interface{} {
return nil
}
c := &SliceCache{
loader: nilSliceLoader,
ttl: MaxDuration,
}
c.launchLoader()
return c
}
func (c *SliceCache) SetLoader(loader func() []interface{}) {
c.loader = loader
}
func (c *SliceCache) SetCacheTtl(duration time.Duration) {
c.ttl = duration
}
func (c *SliceCache) Get() []interface{} {
if c.data == nil {
c.sync()
}
return c.data
}
func (c *SliceCache) String() string {
builder := make([]string, len(c.data))
for i, v := range c.data {
builder[i] = fmt.Sprintf("%+v, ", v)
}
return fmt.Sprintf(
"SliceCache(%+v,%+v,%+v)",
builder,
c.loader,
c.ttl,
)
}
func (c *SliceCache) sync() {
c.data = c.loader()
}
func (c *SliceCache) launchLoader() {
// should only launch once
go func() {
for _ = range time.Tick(c.ttl) {
c.sync()
}
}()
}