-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
memoize_test.go
104 lines (85 loc) · 2.5 KB
/
memoize_test.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gogu
import (
"fmt"
"testing"
"time"
"github.com/esimov/gogu/cache"
"github.com/stretchr/testify/assert"
)
func TestMemoize(t *testing.T) {
assert := assert.New(t)
m := NewMemoizer[string, any](time.Second, time.Minute)
sampleItem := map[string]any{
"foo": "one",
"bar": "two",
"baz": "three",
}
// Here we are simulating an expensive operation.
expensiveOp := func() (*cache.Item[any], error) {
// Here we are simulating an expensive operation.
time.Sleep(500 * time.Millisecond)
foo := FindByKey(sampleItem, func(key string) bool {
return key == "foo"
})
m.Cache.MapToCache(foo, cache.DefaultExpiration)
item, err := m.Cache.Get("foo")
if err != nil {
return nil, err
}
return item, nil
}
assert.Empty(m.Cache.List())
// Caching the result of some expensive fictive operation result.
data, err := m.Memoize("key1", expensiveOp)
assert.NoError(err)
assert.NotEmpty(data)
assert.NotEmpty(m.Cache.List())
item, _ := m.Cache.Get("key1")
assert.Equal("one", item.Val())
// Serving the expensive operation result from the cache. This should return instantly.
// If it would invoked the expensiveOp function this would be introduced a 500 millisecond latency.
start := time.Now()
data, err = m.Memoize("key1", expensiveOp)
after := time.Since(start).Milliseconds()
assert.NoError(err)
assert.NotEmpty(data)
assert.LessOrEqual(int(after), 1)
}
func Example_memoize() {
m := NewMemoizer[string, any](time.Second, time.Minute)
sampleItem := map[string]any{
"foo": "one",
"bar": "two",
"baz": "three",
}
// Here we are simulating an expensive operation.
expensiveOp := func() (*cache.Item[any], error) {
// Here we are simulating an expensive operation.
time.Sleep(500 * time.Millisecond)
foo := FindByKey(sampleItem, func(key string) bool {
return key == "foo"
})
m.Cache.MapToCache(foo, cache.DefaultExpiration)
item, err := m.Cache.Get("foo")
if err != nil {
return nil, err
}
return item, nil
}
// Cache is empty this time.
fmt.Println(m.Cache.List())
// Caching the result of some expensive fictive operation result.
m.Memoize("key1", expensiveOp)
fmt.Println(len(m.Cache.List()))
item, _ := m.Cache.Get("key1")
fmt.Println(item.Val())
// Serving the expensive operation result from the cache. This should return instantly.
// If it would invoked the expensiveOp function this would be introduced a 500 millisecond latency.
data, _ := m.Memoize("key1", expensiveOp)
fmt.Println(data.Val())
// Output:
// map[]
// 2
// one
// one
}