add diff and pdiff for conditions

This commit is contained in:
coral 2017-09-29 17:20:02 +08:00
parent dd56c4b94b
commit 9e48d54465
3 changed files with 60 additions and 0 deletions

View File

@ -94,6 +94,53 @@ func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float {
value = (values[(length/2)-1] + values[length/2]) / 2
}
}
case "diff":
var (
points = series.Points
first float64
i int
)
// get the newest point
for i = len(points) - 1; i >= 0; i-- {
if points[i][0].Valid {
allNull = false
first = points[i][0].Float64
break
}
}
// get other points
points = points[0:i]
for i := len(points) - 1; i >= 0; i-- {
if points[i][0].Valid {
allNull = false
value = first - points[i][0].Float64
break
}
}
case "pdiff":
var (
points = series.Points
first float64
i int
)
// get the newest point
for i = len(points) - 1; i >= 0; i-- {
if points[i][0].Valid {
allNull = false
first = points[i][0].Float64
break
}
}
// get other points
points = points[0:i]
for i := len(points) - 1; i >= 0; i-- {
if points[i][0].Valid {
allNull = false
val := (first - points[i][0].Float64) / points[i][0].Float64 * 100
value = math.Abs(val)
break
}
}
}
if allNull {

View File

@ -80,6 +80,17 @@ func TestSimpleReducer(t *testing.T) {
So(reducer.Reduce(series).Float64, ShouldEqual, float64(3))
})
Convey("diff", func() {
result := testReducer("diff", 30, 40)
So(result, ShouldEqual, float64(10))
})
Convey("pdiff", func() {
result := testReducer("pdiff", 30, 40)
So(result, ShouldEqual, float64(33.33333333333333))
})
})
}

View File

@ -49,6 +49,8 @@ var reducerTypes = [
{text: 'count()', value: 'count'},
{text: 'last()', value: 'last'},
{text: 'median()', value: 'median'},
{text: 'diff()', value: 'diff'},
{text: 'pdiff()', value: 'pdiff'},
];
var noDataModes = [