Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/sparkline/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186406 max_deposit = "5000000ugnot"
sparkline.gno
// Package sparkline renders a numeric series as one line of Unicode block
// characters — ▁▂▃▄▅▆▇█ — so a realm's Render can show a trend inline, with no
// image, no chart library and no client-side code.
//
// Everything is integer math, deliberately. A realm's Render must produce
// byte-identical output on every validating node, and floating point is the
// usual way that quietly stops being true. Scaling here is integer division
// with the rounding rule stated below, so a given series always yields exactly
// the same runes.
//
// Rendering is O(len(values)) and allocates one builder; a realm should bound
// what it feeds in (slice to a window) rather than sparking an unbounded,
// user-grown slice.
//
// A live demo of this package is at
// [r/moul/x/daily/sparklinedemo](/r/nym-moultest123/x/daily/sparklinedemo/v0).
package sparkline
import "strings"
// Levels is the ramp, lowest to highest. A string constant rather than a
// []rune so callers cannot mutate the ramp out from under other realms.
const Levels = "▁▂▃▄▅▆▇█"
// Steps is how many levels the ramp has.
const Steps = 8
// maxInt is the largest int, used to keep the scaling multiply from wrapping.
const maxInt = int(^uint(0) >> 1)
// Ints renders values scaled between their own smallest and largest element.
// An empty series renders as the empty string.
func Ints(values []int) string {
lo, hi, ok := Bounds(values)
if !ok {
return ""
}
return Scaled(values, lo, hi)
}
// Scaled renders values against an explicit [lo, hi] window. Values outside it
// clamp to the ends rather than erroring: a window is chosen for readability
// (0..100 for a percentage, say), and one outlier should not be able to break a
// realm's Render.
//
// A window with hi <= lo is treated as flat; see Level.
func Scaled(values []int, lo, hi int) string {
if len(values) == 0 {
return ""
}
ramp := []rune(Levels)
var b strings.Builder
for _, v := range values {
b.WriteRune(ramp[Level(v, lo, hi)])
}
return b.String()
}
// Level maps v within [lo, hi] to a ramp index in [0, Steps-1].
//
// Rounding is floor, so only a value at hi itself reaches the top of the ramp;
// everything below it rounds down. That makes the maximum visually distinct,
// which is what a reader is looking for in a sparkline.
//
// A flat window (hi <= lo) maps everything to the MIDDLE of the ramp, not the
// bottom: a series that sits unchanged at 1000 carries no shape, but drawing it
// along the floor would read as "zero", which is a different and wrong claim.
func Level(v, lo, hi int) int {
if hi <= lo {
return Steps / 2
}
if v <= lo {
return 0
}
if v >= hi {
return Steps - 1
}
span, d, top := hi-lo, v-lo, Steps-1
if span <= 0 {
// hi-lo wrapped: the window is wider than an int can express, so there
// is no usable ramp. Split at the midpoint, computed without overflowing.
if v < lo/2+hi/2 {
return 0
}
return Steps - 1
}
// d*top would wrap on an extreme span; halve both until it cannot. The
// chosen bucket is unchanged for any realistic series, and off by at most
// one level for the pathological ones this protects against.
for span > maxInt/top {
span >>= 1
d >>= 1
}
return d * top / span
}
// Bounds returns the smallest and largest value in values. ok is false when
// values is empty, in which case lo and hi are zero.
func Bounds(values []int) (lo, hi int, ok bool) {
if len(values) == 0 {
return 0, 0, false
}
lo, hi = values[0], values[0]
for _, v := range values[1:] {
if v < lo {
lo = v
}
if v > hi {
hi = v
}
}
return lo, hi, true
}
sparkline_test.gno
package sparkline
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestInts(t *testing.T) {
tests := []struct {
name string
values []int
want string
}{
{"empty", nil, ""},
{"empty slice", []int{}, ""},
// A single value is its own min and max, i.e. flat: mid-ramp.
{"single", []int{42}, "▅"},
{"flat", []int{7, 7, 7}, "▅▅▅"},
{"flat at zero", []int{0, 0}, "▅▅"},
{"two apart", []int{0, 1}, "▁█"},
{"ramp", []int{0, 1, 2, 3, 4, 5, 6, 7}, "▁▂▃▄▅▆▇█"},
{"descending", []int{7, 6, 5, 4, 3, 2, 1, 0}, "█▇▆▅▄▃▂▁"},
{"negatives only", []int{-7, -4, 0}, "▁▄█"},
{"spans zero", []int{-7, 0, 7}, "▁▄█"},
{"wide range", []int{0, 50, 100}, "▁▄█"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
uassert.Equal(t, tt.want, Ints(tt.values))
})
}
}
func TestScaledClampsOutliers(t *testing.T) {
// The window is the contract: anything outside it pins to an end rather
// than rescaling the picture or panicking.
uassert.Equal(t, "▁▁▄██", Scaled([]int{-100, 0, 50, 100, 999}, 0, 100))
}
func TestScaledEmpty(t *testing.T) {
uassert.Equal(t, "", Scaled(nil, 0, 10))
}
func TestScaledFlatWindow(t *testing.T) {
// hi <= lo carries no shape; every value lands mid-ramp.
uassert.Equal(t, "▅▅▅", Scaled([]int{1, 500, 9}, 5, 5))
uassert.Equal(t, "▅▅", Scaled([]int{1, 2}, 10, 3))
}
func TestLevel(t *testing.T) {
tests := []struct {
name string
v, lo, hi int
want int
}{
{"at floor", 0, 0, 7, 0},
{"at ceiling", 7, 0, 7, 7},
{"below floor clamps", -5, 0, 7, 0},
{"above ceiling clamps", 99, 0, 7, 7},
{"flat window", 3, 5, 5, Steps / 2},
{"inverted window", 3, 9, 2, Steps / 2},
// Floor rounding: only hi itself reaches the top.
{"just below ceiling", 99, 0, 100, 6},
{"exact ceiling", 100, 0, 100, 7},
{"midpoint", 50, 0, 100, 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
uassert.Equal(t, tt.want, Level(tt.v, tt.lo, tt.hi))
})
}
}
// Level must stay inside the ramp for every input, including the extremes that
// make the scaling arithmetic wrap. An out-of-range index here would panic the
// realm that called Scaled, so this is the load-bearing invariant.
func TestLevelAlwaysInRange(t *testing.T) {
const minInt = -maxInt - 1
vals := []int{minInt, -maxInt, -1000, -1, 0, 1, 1000, maxInt}
windows := [][2]int{
{0, 7}, {0, 100}, {-100, 100}, {5, 5}, {9, 2},
{minInt, maxInt}, // span wraps int
{0, maxInt}, // span survives, but d*top would wrap
{minInt, 0},
}
for _, w := range windows {
for _, v := range vals {
got := Level(v, w[0], w[1])
if got < 0 || got >= Steps {
t.Fatalf("Level(%d, %d, %d) = %d, outside [0,%d)", v, w[0], w[1], got, Steps)
}
}
}
}
// The huge-span path halves its way down to safe arithmetic; it must still be
// monotonic, or the picture would lie about the direction of the trend.
func TestLevelMonotonicOnHugeSpan(t *testing.T) {
prev := -1
for _, v := range []int{0, maxInt / 8, maxInt / 4, maxInt / 2, maxInt} {
got := Level(v, 0, maxInt)
if got < prev {
t.Fatalf("Level(%d, 0, maxInt) = %d, went down from %d", v, got, prev)
}
prev = got
}
}
func TestBounds(t *testing.T) {
lo, hi, ok := Bounds([]int{3, -1, 9, 4})
uassert.True(t, ok, "non-empty series should report ok")
uassert.Equal(t, -1, lo)
uassert.Equal(t, 9, hi)
lo, hi, ok = Bounds(nil)
uassert.False(t, ok, "empty series should report not-ok")
uassert.Equal(t, 0, lo)
uassert.Equal(t, 0, hi)
}
func TestLevelsRampIsEightRunes(t *testing.T) {
// Scaled indexes this ramp by Level's result, so the two must agree.
uassert.Equal(t, Steps, len([]rune(Levels)))
}