fix gauge percentage calculation for the case when min value is not zero
This commit is contained in:
parent
cec214dc0d
commit
b45b3882b0
|
@ -82,10 +82,7 @@ func (g *Gauge) Draw(buffer *ui.Buffer) {
|
|||
|
||||
g.Block.Draw(buffer)
|
||||
|
||||
percent := 0.0
|
||||
if g.curValue != 0 && g.maxValue != g.minValue {
|
||||
percent = (100 * g.curValue) / (g.maxValue - g.minValue)
|
||||
}
|
||||
percent := calculatePercent(g)
|
||||
|
||||
var label string
|
||||
if g.percentOnly {
|
||||
|
@ -121,3 +118,10 @@ func (g *Gauge) Draw(buffer *ui.Buffer) {
|
|||
|
||||
component.RenderAlert(g.Alert, g.Rectangle, buffer)
|
||||
}
|
||||
|
||||
func calculatePercent(g *Gauge) float64 {
|
||||
if g.curValue != g.minValue && g.maxValue != g.minValue {
|
||||
return (100 * (g.curValue - g.minValue)) / (g.maxValue - g.minValue)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
package gauge
|
||||
|
||||
import "testing"
|
||||
|
||||
func Test_calculatePercent(t *testing.T) {
|
||||
type args struct {
|
||||
g *Gauge
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want float64
|
||||
}{
|
||||
{"should calculate percent between 0 and 60", args{&Gauge{minValue: 0, maxValue: 60, curValue: 45}}, 75},
|
||||
{"should calculate percent between 10 and 60", args{&Gauge{minValue: 10, maxValue: 60, curValue: 59}}, 98},
|
||||
{"should calculate percent between -20 and 60", args{&Gauge{minValue: -20, maxValue: 60, curValue: 0}}, 25},
|
||||
{"should calculate percent when cur value = min value", args{&Gauge{minValue: -10, maxValue: 60, curValue: -10}}, 0},
|
||||
{"should calculate percent when min value = max value", args{&Gauge{minValue: -124, maxValue: -124, curValue: -124}}, 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := calculatePercent(tt.args.g); got != tt.want {
|
||||
t.Errorf("calculatePercent() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue