RosettaCodeData/Task/Sparkline-in-unicode/Pluto/sparkline-in-unicode.pluto
2026-04-30 12:34:36 -04:00

53 lines
1.4 KiB
Text

require "io2"
-- Split a string using one or more whitespace or comma characters as the separator.
local function split2(s)
-- Replace all commas with spaces.
s = s:replace(",", " ")
-- Split on spaces and remove empty entries.
return s:split(" "):filter(|e| -> #e > 0):reorder()
end
local function spark(s0)
local ss = split2(s0)
local n = #ss
local vs = table.create(n)
local min = math.huge
local max = -min
for i, s in ss do
local v = tonumber(s)
if math.isnan(v) or v == math.huge or v == -math.huge then
error("Infinities and NaN not supported.")
end
if v < min then min = v end
if v > max then max = v end
vs[i] = v
end
local sp
if min == max then
sp = string.rep("▄", n)
else
local rs = table.create(n)
local f = 8 / (max - min)
for j, v in vs do
local i = math.floor(f * (v - min))
if i > 7 then i = 7 end
rs[j] = utf8.char(0x2581 + i)
end
sp = rs:concat()
end
return sp, n, min, max
end
while true do
local numbers = io.readStr("Numbers please separated by spaces/commas or q to quit:\n", 1)
if !numbers then break end
local s, n, min, max = spark(numbers)
if n == 1 then
print($"1 value = {min}")
else
print($"{n} values. Min: {min} Max: {max}")
end
print(s)
print()
end