Scala: An ASCII Sparkline chart function (source code)

UPDATE: The latest version of this code is at github.com/alvinj/TextPlottingUtils.

Creating an ASCII version of a Sparkline chart — also known as a Win/Loss chart — in Scala turned out to take just a few lines of code, as shown in this source code:

/**
 * This function returns an ASCII Sparkline chart like this as a
 * multiline String:
 *
 *     | ||| |   ||
 *      |   | |||
 *
 * when given an input like this:
 *
 *     Seq(true, false, true, true, true, false, true, false, false, false, true, true)
 *
 * @param results `true` for a win (or gain), `false` otherwise.
 * @return A multiline String, as shown in the example above.
 */
def asciiSparklineChart(results: Seq[Boolean]): String =
    if results.isEmpty then
        ""
    else
        val topRow = results.map(if _ then "|" else " ").mkString
        val bottomRow = results.map(if _ then " " else "|").mkString
        s"$topRow\n$bottomRow"

The body of the code can also be implemented as a Scala match expression, but I think the if/then code is easier to read in this case.

I think a simple little example like this helps to demonstrate the beauty and elegance of the Scala programming language.

Possible improvements

If you also want to implement this Scala Sparkline function so it returns an ASCII chart like this, that’s also a simple change, as you can imagine:

| ||| |   ||
------------
 |   | |||

Other things you can do are to let the function caller specify the character they want to use for the up and down symbols, as well as the dividing line. There are probably better UTF-8 symbols you can use, but I haven’t looked into that yet.