@@ -11,17 +11,36 @@ type Cache[K comparable, V any] struct {
11
11
items map [K ]* entry [K , V ]
12
12
}
13
13
14
- // NewCache creates a new LFU cache whose capacity is the default size (128).
15
- func NewCache [K comparable , V any ]() * Cache [K , V ] {
16
- return NewCacheWithCap [K , V ](128 )
14
+ // Option is an option for LFU cache.
15
+ type Option func (* options )
16
+
17
+ type options struct {
18
+ capacity int
19
+ }
20
+
21
+ func newOptions () * options {
22
+ return & options {
23
+ capacity : 128 ,
24
+ }
17
25
}
18
26
19
- // NewCacheWithCap creates a new LFU cache whose capacity is the specified size.
20
- func NewCacheWithCap [K comparable , V any ](cap int ) * Cache [K , V ] {
27
+ // WithCapacity is an option to set cache capacity.
28
+ func WithCapacity (cap int ) Option {
29
+ return func (o * options ) {
30
+ o .capacity = cap
31
+ }
32
+ }
33
+
34
+ // NewCache creates a new LFU cache whose capacity is the default size (128).
35
+ func NewCache [K comparable , V any ](opts ... Option ) * Cache [K , V ] {
36
+ o := newOptions ()
37
+ for _ , optFunc := range opts {
38
+ optFunc (o )
39
+ }
21
40
return & Cache [K , V ]{
22
- cap : cap ,
23
- queue : newPriorityQueue [K , V ](cap ),
24
- items : make (map [K ]* entry [K , V ], cap ),
41
+ cap : o . capacity ,
42
+ queue : newPriorityQueue [K , V ](o . capacity ),
43
+ items : make (map [K ]* entry [K , V ], o . capacity ),
25
44
}
26
45
}
27
46
0 commit comments