Scala plain-text table with aligned columns
Scala
def renderTable(headers: Seq[String], rows: Seq[Seq[String]]): String =
val allRows = headers +: rows
val widths = headers.indices.map(i => allRows.map(_.lift(i).getOrElse("").length).max)
def pad(cell: String, width: Int): String =
cell + " " * (width - cell.length)
def format(row: Seq[String]): String =
row.zipWithIndex.map((cell, i) => pad(cell, widths(i))).mkString(" ")
val divider = widths.map(width => "-" * width).mkString(" ")
(format(headers) +: divider +: rows.map(format)).mkString("\n")
def printTable(headers: Seq[String], rows: Seq[Seq[String]]): Unit =
println(renderTable(headers, rows))