Friday, August 11, 2023

Scala Ascii Table Extension

object AsciiTableExtensions {
case class Col[T](Caption: String, PadWidth: Int, ValueFunction: T => String = (t: T) => t.toString)
implicit class AsciiTableExtensions[T](iterable: Iterable[T]) {
private def printSeparatorRow(cols: Seq[Col[T]]): Unit = {
cols.foreach(col => print("+" + "-" * (col.PadWidth + 2)))
println("+")
}
def printAsciiTable(cols: Seq[Col[T]]): Unit = {
printSeparatorRow(cols) // Print separator row before column header
// Print column headers
cols.foreach(col => print("| " + col.Caption.padTo(col.PadWidth, ' ') + " "))
println("|")
printSeparatorRow(cols) // Print separator row after column header
// Print table rows
iterable.foreach { element =>
cols.foreach { col =>
val value = col.ValueFunction(element)
print("| " + value.padTo(col.PadWidth, ' ') + " ")
}
println("|")
}
printSeparatorRow(cols) // Print separator row at the end of the table
println(s"(rows: ${iterable.size}, cols: ${cols.size})")
}
}
}
object Main extends App {
import AsciiTableExtensions._
case class Person(name: String, age: Int)
val people = Seq(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 28)
)
val cols = Seq(
Col[Person]("Name", 15, _.name),
Col[Person]("Age", 5, _.age.toString),
Col[Person]("Default", 20) // Changed PadWidth to 20
)
people.printAsciiTable(cols)
}

No comments: