squiggle/packages/squiggle-lang/src/rescript/utility/Sparklines.res

27 lines
891 B
Plaintext
Raw Normal View History

// Port of Sindre Sorhus' Sparkly to Rescript
// reference implementation: https://github.com/sindresorhus/sparkly
// Omitting rgb "fire" style, so no `chalk` dependency
2022-03-29 19:27:23 +00:00
// Omitting: NaN handling, special consideration for constant data.
2022-03-29 20:31:08 +00:00
let ticks = [`▁`, `▂`, `▃`, `▄`, `▅`, `▆`, `▇`, `█`]
2022-03-29 14:55:36 +00:00
2022-03-29 20:31:08 +00:00
let _ticksLength = E.A.length(ticks)
2022-03-29 15:05:27 +00:00
2022-03-29 20:31:08 +00:00
let _heightToTickIndex = (maximum: float, v: float) => {
2022-03-29 21:00:20 +00:00
let suggestedTickIndex = Js.Math.ceil_int(v /. maximum *. Belt.Int.toFloat(_ticksLength)) - 1
max(suggestedTickIndex, 0)
2022-03-29 20:31:08 +00:00
}
2022-03-29 19:27:23 +00:00
2022-03-29 20:31:08 +00:00
let create = (relativeHeights: array<float>, ~maximum=?, ()) => {
if E.A.length(relativeHeights) === 0 {
""
} else {
2022-03-29 21:00:20 +00:00
let maximum = maximum->E.O2.default(E.A.max(relativeHeights)->E.O2.toExn(""))
2022-03-29 20:31:08 +00:00
relativeHeights
2022-03-29 21:00:20 +00:00
->E.A2.fmap(_heightToTickIndex(maximum))
->E.A2.fmap(r => E.A.get(ticks, r)->E.O2.toExn(""))
->E.A2.joinWith("")
2022-03-29 20:31:08 +00:00
}
}