fix: simplify stoch indicator using float64slice. add ToReverseArray

This commit is contained in:
zenix 2022-04-07 12:29:15 +09:00
parent 339d36d61b
commit be0755d755
2 changed files with 24 additions and 48 deletions

View File

@ -83,54 +83,10 @@ func (inc *STOCH) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func (inc *STOCH) GetD() *DSeries {
return &DSeries{inc}
func (inc *STOCH) GetD() types.Series {
return inc.D
}
func (inc *STOCH) GetK() *KSeries {
return &KSeries{inc}
func (inc *STOCH) GetK() types.Series {
return inc.K
}
type DSeries struct {
*STOCH
}
func (inc *DSeries) Last() float64 {
return inc.LastD()
}
func (inc *DSeries) Length() int {
return len(inc.D)
}
func (inc *DSeries) Index(i int) float64 {
length := len(inc.D)
if length == 0 || length-i-1 < 0 {
return 0
}
return inc.D[length-i-1]
}
var _ types.Series = &DSeries{}
type KSeries struct {
*STOCH
}
func (inc *KSeries) Last() float64 {
return inc.LastK()
}
func (inc *KSeries) Index(i int) float64 {
length := len(inc.K)
if length == 0 || length-i-1 < 0 {
return 0
}
return inc.K[length-i-1]
}
func (inc *KSeries) Length() int {
return len(inc.K)
}
var _ types.Series = &KSeries{}

View File

@ -423,3 +423,23 @@ func ToArray(a Series, limit ...int) (result []float64) {
}
return
}
// Similar to ToArray but in reverse order.
// Useful when you want to cache series' calculated result as float64 array
// the then reuse the result in multiple places (so that no recalculation will be triggered)
//
// notice that the return type is a Float64Slice, which implements the Series interface
func ToReverseArray(a Series, limit ...int) (result Float64Slice) {
l := -1
if len(limit) > 0 {
l = limit[0]
}
if l < a.Length() {
l = a.Length()
}
result = make([]float64, l, l)
for i := 0; i < l; i++ {
result[l-i-1] = a.Index(i)
}
return
}