forked from sdcoffey/techan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cached_indicator.go
46 lines (38 loc) · 1.21 KB
/
cached_indicator.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
package techan
import "github.com/sdcoffey/big"
type resultCache []*big.Decimal
type cachedIndicator interface {
Indicator
cache() resultCache
setCache(cache resultCache)
windowSize() int
}
func cacheResult(indicator cachedIndicator, index int, val big.Decimal) {
if index < len(indicator.cache()) {
indicator.cache()[index] = &val
} else if index == len(indicator.cache()) {
indicator.setCache(append(indicator.cache(), &val))
} else {
expandResultCache(indicator, index+1)
cacheResult(indicator, index, val)
}
}
func expandResultCache(indicator cachedIndicator, newSize int) {
sizeDiff := newSize - len(indicator.cache())
expansion := make([]*big.Decimal, sizeDiff)
indicator.setCache(append(indicator.cache(), expansion...))
}
func returnIfCached(indicator cachedIndicator, index int, firstValueFallback func(int) big.Decimal) *big.Decimal {
if index >= len(indicator.cache()) {
expandResultCache(indicator, index+1)
} else if index < indicator.windowSize()-1 {
return &big.ZERO
} else if val := indicator.cache()[index]; val != nil {
return val
} else if index == indicator.windowSize()-1 {
value := firstValueFallback(index)
cacheResult(indicator, index, value)
return &value
}
return nil
}