63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
func sparklinePath(values []int, w, h int) string {
|
|
return sparklinePathInternal(intsTo64(values), w, h, false)
|
|
}
|
|
|
|
func sparklinePathInternal(values []int64, w, h int, closed bool) string {
|
|
if len(values) == 0 || w <= 0 || h <= 0 {
|
|
return ""
|
|
}
|
|
minV, maxV := values[0], values[0]
|
|
for _, v := range values {
|
|
if v < minV {
|
|
minV = v
|
|
}
|
|
if v > maxV {
|
|
maxV = v
|
|
}
|
|
}
|
|
span := float64(maxV - minV)
|
|
if span == 0 {
|
|
span = 1
|
|
}
|
|
stepX := float64(w)
|
|
if len(values) > 1 {
|
|
stepX = float64(w) / float64(len(values)-1)
|
|
}
|
|
var b strings.Builder
|
|
for i, v := range values {
|
|
x := float64(i) * stepX
|
|
// Invert Y so larger values are higher.
|
|
y := float64(h) - (float64(v-minV)/span)*float64(h)
|
|
if i == 0 {
|
|
fmt.Fprintf(&b, "M%.1f,%.1f", x, y)
|
|
} else {
|
|
fmt.Fprintf(&b, " L%.1f,%.1f", x, y)
|
|
}
|
|
}
|
|
if closed {
|
|
// Close the path to the baseline so the area fill renders cleanly.
|
|
fmt.Fprintf(&b, " L%.1f,%.1f L%.1f,%.1f Z", float64(w), float64(h), 0.0, float64(h))
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func intsTo64(in []int) []int64 {
|
|
out := make([]int64, len(in))
|
|
for i, v := range in {
|
|
out[i] = int64(v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func main() {
|
|
got := sparklinePath([]int{0, 10}, 100, 20)
|
|
|
|
fmt.Println(got)
|
|
}
|